1 //! Tools and utilities
3 //! This is a collection of small and useful tools.
5 use std
::collections
::HashMap
;
6 use std
::hash
::BuildHasher
;
7 use std
::fs
::{File, OpenOptions}
;
8 use std
::io
::{self, BufRead, ErrorKind, Read}
;
9 use std
::os
::unix
::io
::{AsRawFd, RawFd}
;
11 use std
::time
::Duration
;
13 use anyhow
::{bail, format_err, Error}
;
14 use serde_json
::Value
;
15 use openssl
::hash
::{hash, DigestBytes, MessageDigest}
;
16 use percent_encoding
::AsciiSet
;
18 use proxmox
::tools
::vec
;
20 pub use proxmox
::tools
::fd
::Fd
;
35 mod wrapped_reader_stream
;
36 pub use wrapped_reader_stream
::*;
38 mod std_channel_writer
;
39 pub use std_channel_writer
::*;
44 pub use process_locker
::*;
47 pub use file_logger
::*;
50 pub use broadcast_future
::*;
52 /// The `BufferedRead` trait provides a single function
53 /// `buffered_read`. It returns a reference to an internal buffer. The
54 /// purpose of this traid is to avoid unnecessary data copies.
55 pub trait BufferedRead
{
56 /// This functions tries to fill the internal buffers, then
57 /// returns a reference to the available data. It returns an empty
58 /// buffer if `offset` points to the end of the file.
59 fn buffered_read(&mut self, offset
: u64) -> Result
<&[u8], Error
>;
62 /// Directly map a type into a binary buffer. This is mostly useful
63 /// for reading structured data from a byte stream (file). You need to
64 /// make sure that the buffer location does not change, so please
65 /// avoid vec resize while you use such map.
67 /// This function panics if the buffer is not large enough.
68 pub fn map_struct
<T
>(buffer
: &[u8]) -> Result
<&T
, Error
> {
69 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
70 bail
!("unable to map struct - buffer too small");
72 Ok(unsafe { &*(buffer.as_ptr() as *const T) }
)
75 /// Directly map a type into a mutable binary buffer. This is mostly
76 /// useful for writing structured data into a byte stream (file). You
77 /// need to make sure that the buffer location does not change, so
78 /// please avoid vec resize while you use such map.
80 /// This function panics if the buffer is not large enough.
81 pub fn map_struct_mut
<T
>(buffer
: &mut [u8]) -> Result
<&mut T
, Error
> {
82 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
83 bail
!("unable to map struct - buffer too small");
85 Ok(unsafe { &mut *(buffer.as_ptr() as *mut T) }
)
88 /// Create a file lock using fntl. This function allows you to specify
89 /// a timeout if you want to avoid infinite blocking.
90 pub fn lock_file
<F
: AsRawFd
>(
93 timeout
: Option
<Duration
>,
94 ) -> Result
<(), Error
> {
95 let lockarg
= if exclusive
{
96 nix
::fcntl
::FlockArg
::LockExclusive
98 nix
::fcntl
::FlockArg
::LockShared
101 let timeout
= match timeout
{
103 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
109 // unblock the timeout signal temporarily
110 let _sigblock_guard
= timer
::unblock_timeout_signal();
112 // setup a timeout timer
113 let mut timer
= timer
::Timer
::create(
114 timer
::Clock
::Realtime
,
115 timer
::TimerEvent
::ThisThreadSignal(timer
::SIGTIMEOUT
),
119 timer
::TimerSpec
::new()
120 .value(Some(timeout
))
121 .interval(Some(Duration
::from_millis(10))),
124 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
128 /// Open or create a lock file (append mode). Then try to
129 /// acquire a lock using `lock_file()`.
130 pub fn open_file_locked
<P
: AsRef
<Path
>>(path
: P
, timeout
: Duration
) -> Result
<File
, Error
> {
131 let path
= path
.as_ref();
132 let mut file
= match OpenOptions
::new().create(true).append(true).open(path
) {
134 Err(err
) => bail
!("Unable to open lock {:?} - {}", path
, err
),
136 match lock_file(&mut file
, true, Some(timeout
)) {
138 Err(err
) => bail
!("Unable to acquire lock {:?} - {}", path
, err
),
142 /// Split a file into equal sized chunks. The last chunk may be
143 /// smaller. Note: We cannot implement an `Iterator`, because iterators
144 /// cannot return a borrowed buffer ref (we want zero-copy)
145 pub fn file_chunker
<C
, R
>(mut file
: R
, chunk_size
: usize, mut chunk_cb
: C
) -> Result
<(), Error
>
147 C
: FnMut(usize, &[u8]) -> Result
<bool
, Error
>,
150 const READ_BUFFER_SIZE
: usize = 4 * 1024 * 1024; // 4M
152 if chunk_size
> READ_BUFFER_SIZE
{
153 bail
!("chunk size too large!");
156 let mut buf
= vec
::undefined(READ_BUFFER_SIZE
);
159 let mut file_pos
= 0;
162 let mut tmp
= &mut buf
[..];
163 // try to read large portions, at least chunk_size
164 while pos
< chunk_size
{
165 match file
.read(tmp
) {
172 if pos
> chunk_size
{
177 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> { /* try again */ }
178 Err(e
) => bail
!("read chunk failed - {}", e
.to_string()),
182 while start
+ chunk_size
<= pos
{
183 if !(chunk_cb
)(file_pos
, &buf
[start
..start
+ chunk_size
])?
{
186 file_pos
+= chunk_size
;
191 (chunk_cb
)(file_pos
, &buf
[start
..pos
])?
;
192 //file_pos += pos - start;
196 let rest
= pos
- start
;
198 let ptr
= buf
.as_mut_ptr();
200 std
::ptr
::copy_nonoverlapping(ptr
.add(start
), ptr
, rest
);
212 pub fn json_object_to_query(data
: Value
) -> Result
<String
, Error
> {
213 let mut query
= url
::form_urlencoded
::Serializer
::new(String
::new());
215 let object
= data
.as_object().ok_or_else(|| {
216 format_err
!("json_object_to_query: got wrong data type (expected object).")
219 for (key
, value
) in object
{
222 query
.append_pair(key
, &b
.to_string());
224 Value
::Number(n
) => {
225 query
.append_pair(key
, &n
.to_string());
227 Value
::String(s
) => {
228 query
.append_pair(key
, &s
);
230 Value
::Array(arr
) => {
234 query
.append_pair(key
, &b
.to_string());
236 Value
::Number(n
) => {
237 query
.append_pair(key
, &n
.to_string());
239 Value
::String(s
) => {
240 query
.append_pair(key
, &s
);
243 "json_object_to_query: unable to handle complex array data types."
248 _
=> bail
!("json_object_to_query: unable to handle complex data types."),
255 pub fn required_string_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<&'a
str, Error
> {
256 match param
[name
].as_str() {
258 None
=> bail
!("missing parameter '{}'", name
),
262 pub fn required_string_property
<'a
>(param
: &'a Value
, name
: &str) -> Result
<&'a
str, Error
> {
263 match param
[name
].as_str() {
265 None
=> bail
!("missing property '{}'", name
),
269 pub fn required_integer_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<i64, Error
> {
270 match param
[name
].as_i64() {
272 None
=> bail
!("missing parameter '{}'", name
),
276 pub fn required_integer_property
<'a
>(param
: &'a Value
, name
: &str) -> Result
<i64, Error
> {
277 match param
[name
].as_i64() {
279 None
=> bail
!("missing property '{}'", name
),
283 pub fn required_array_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<Vec
<Value
>, Error
> {
284 match param
[name
].as_array() {
285 Some(s
) => Ok(s
.to_vec()),
286 None
=> bail
!("missing parameter '{}'", name
),
290 pub fn required_array_property
<'a
>(param
: &'a Value
, name
: &str) -> Result
<Vec
<Value
>, Error
> {
291 match param
[name
].as_array() {
292 Some(s
) => Ok(s
.to_vec()),
293 None
=> bail
!("missing property '{}'", name
),
297 pub fn complete_file_name
<S
: BuildHasher
>(arg
: &str, _param
: &HashMap
<String
, String
, S
>) -> Vec
<String
> {
298 let mut result
= vec
![];
300 use nix
::fcntl
::AtFlags
;
301 use nix
::fcntl
::OFlag
;
302 use nix
::sys
::stat
::Mode
;
304 let mut dirname
= std
::path
::PathBuf
::from(if arg
.is_empty() { "./" }
else { arg }
);
306 let is_dir
= match nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &dirname
, AtFlags
::empty()) {
307 Ok(stat
) => (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
,
312 if let Some(parent
) = dirname
.parent() {
313 dirname
= parent
.to_owned();
318 match nix
::dir
::Dir
::openat(libc
::AT_FDCWD
, &dirname
, OFlag
::O_DIRECTORY
, Mode
::empty()) {
320 Err(_
) => return result
,
323 for item
in dir
.iter() {
324 if let Ok(entry
) = item
{
325 if let Ok(name
) = entry
.file_name().to_str() {
326 if name
== "." || name
== ".." {
329 let mut newpath
= dirname
.clone();
333 nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &newpath
, AtFlags
::empty())
335 if (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
{
337 if let Some(newpath
) = newpath
.to_str() {
338 result
.push(newpath
.to_owned());
343 if let Some(newpath
) = newpath
.to_str() {
344 result
.push(newpath
.to_owned());
353 /// Scan directory for matching file names.
355 /// Scan through all directory entries and call `callback()` function
356 /// if the entry name matches the regular expression. This function
357 /// used unix `openat()`, so you can pass absolute or relative file
358 /// names. This function simply skips non-UTF8 encoded names.
359 pub fn scandir
<P
, F
>(
362 regex
: ®ex
::Regex
,
364 ) -> Result
<(), Error
>
366 F
: FnMut(RawFd
, &str, nix
::dir
::Type
) -> Result
<(), Error
>,
367 P
: ?Sized
+ nix
::NixPath
,
369 for entry
in self::fs
::scan_subdir(dirfd
, path
, regex
)?
{
371 let file_type
= match entry
.file_type() {
372 Some(file_type
) => file_type
,
373 None
=> bail
!("unable to detect file type"),
378 unsafe { entry.file_name_utf8_unchecked() }
,
385 /// Shortcut for md5 sums.
386 pub fn md5sum(data
: &[u8]) -> Result
<DigestBytes
, Error
> {
387 hash(MessageDigest
::md5(), data
).map_err(Error
::from
)
390 pub fn get_hardware_address() -> Result
<String
, Error
> {
391 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
393 let contents
= proxmox
::tools
::fs
::file_get_contents(FILENAME
)?
;
394 let digest
= md5sum(&contents
)?
;
396 Ok(proxmox
::tools
::bin_to_hex(&digest
))
399 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
400 if digest1
!= digest2
{
401 bail
!("detected modified configuration - file changed by other user? Try again.");
406 /// Extract authentication cookie from cookie header.
407 /// We assume cookie_name is already url encoded.
408 pub fn extract_auth_cookie(cookie
: &str, cookie_name
: &str) -> Option
<String
> {
409 for pair
in cookie
.split('
;'
) {
410 let (name
, value
) = match pair
.find('
='
) {
411 Some(i
) => (pair
[..i
].trim(), pair
[(i
+ 1)..].trim()),
412 None
=> return None
, // Cookie format error
415 if name
== cookie_name
{
416 use percent_encoding
::percent_decode
;
417 if let Ok(value
) = percent_decode(value
.as_bytes()).decode_utf8() {
418 return Some(value
.into());
420 return None
; // Cookie format error
428 pub fn join(data
: &Vec
<String
>, sep
: char) -> String
{
429 let mut list
= String
::new();
432 if !list
.is_empty() {
441 /// Detect modified configuration files
443 /// This function fails with a reasonable error message if checksums do not match.
444 pub fn detect_modified_configuration_file(digest1
: &[u8;32], digest2
: &[u8;32]) -> Result
<(), Error
> {
445 if digest1
!= digest2
{
446 bail
!("detected modified configuration - file changed by other user? Try again.");
451 /// normalize uri path
453 /// Do not allow ".", "..", or hidden files ".XXXX"
454 /// Also remove empty path components
455 pub fn normalize_uri_path(path
: &str) -> Result
<(String
, Vec
<&str>), Error
> {
456 let items
= path
.split('
/'
);
458 let mut path
= String
::new();
459 let mut components
= vec
![];
465 if name
.starts_with('
.'
) {
466 bail
!("Path contains illegal components.");
470 components
.push(name
);
473 Ok((path
, components
))
476 /// Helper to check result from std::process::Command output
478 /// The exit_code_check() function should return true if the exit code
479 /// is considered successful.
480 pub fn command_output(
481 output
: std
::process
::Output
,
482 exit_code_check
: Option
<fn(i32) -> bool
>
483 ) -> Result
<String
, Error
> {
485 if !output
.status
.success() {
486 match output
.status
.code() {
488 let is_ok
= match exit_code_check
{
489 Some(check_fn
) => check_fn(code
),
493 let msg
= String
::from_utf8(output
.stderr
)
494 .map(|m
| if m
.is_empty() { String::from("no error message") }
else { m }
)
495 .unwrap_or_else(|_
| String
::from("non utf8 error message (suppressed)"));
497 bail
!("status code: {} - {}", code
, msg
);
500 None
=> bail
!("terminated by signal"),
504 let output
= String
::from_utf8(output
.stdout
)?
;
510 pub fn fd_change_cloexec(fd
: RawFd
, on
: bool
) -> Result
<(), Error
> {
511 use nix
::fcntl
::{fcntl, FdFlag, F_GETFD, F_SETFD}
;
512 let mut flags
= FdFlag
::from_bits(fcntl(fd
, F_GETFD
)?
)
513 .ok_or_else(|| format_err
!("unhandled file flags"))?
; // nix crate is stupid this way...
514 flags
.set(FdFlag
::FD_CLOEXEC
, on
);
515 fcntl(fd
, F_SETFD(flags
))?
;
519 static mut SHUTDOWN_REQUESTED
: bool
= false;
521 pub fn request_shutdown() {
523 SHUTDOWN_REQUESTED
= true;
525 crate::server
::server_shutdown();
529 pub fn shutdown_requested() -> bool
{
530 unsafe { SHUTDOWN_REQUESTED }
533 pub fn fail_on_shutdown() -> Result
<(), Error
> {
534 if shutdown_requested() {
535 bail
!("Server shutdown requested - aborting task");
540 // wrap nix::unistd::pipe2 + O_CLOEXEC into something returning guarded file descriptors
541 pub fn pipe() -> Result
<(Fd
, Fd
), Error
> {
542 let (pin
, pout
) = nix
::unistd
::pipe2(nix
::fcntl
::OFlag
::O_CLOEXEC
)?
;
543 Ok((Fd(pin
), Fd(pout
)))
546 /// An easy way to convert types to Any
548 /// Mostly useful to downcast trait objects (see RpcEnvironment).
550 fn as_any(&self) -> &dyn Any
;
553 impl<T
: Any
> AsAny
for T
{
554 fn as_any(&self) -> &dyn Any
{
559 /// This used to be: `SIMPLE_ENCODE_SET` plus space, `"`, `#`, `<`, `>`, backtick, `?`, `{`, `}`
560 pub const DEFAULT_ENCODE_SET
: &AsciiSet
= &percent_encoding
::CONTROLS
// 0..1f and 7e
561 // The SIMPLE_ENCODE_SET adds space and anything >= 0x7e (7e itself is already included above)
564 // the DEFAULT_ENCODE_SET added:
575 /// Get an iterator over lines of a file, skipping empty lines and comments (lines starting with a
577 pub fn file_get_non_comment_lines<P: AsRef<Path>>(
579 ) -> Result<impl Iterator<Item = io::Result<String>>, Error> {
580 let path = path.as_ref();
582 Ok(io::BufReader::new(
583 File::open(path).map_err(|err| format_err!("error opening {:?}
: {}
", path, err))?,
586 .filter_map(|line| match line {
588 let line = line.trim();
589 if line.is_empty() || line.starts_with('#') {
592 Some(Ok(line.to_string()))
595 Err(err) => Some(Err(err)),