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
;
17 use std
::os
::unix
::io
::RawFd
;
18 use std
::os
::unix
::io
::AsRawFd
;
20 use std
::collections
::HashMap
;
22 use serde_json
::Value
;
25 pub mod wrapped_reader_stream
;
36 pub use file_logger
::*;
38 /// Macro to write error-handling blocks (like perl eval {})
42 /// # #[macro_use] extern crate proxmox_backup;
44 /// # let some_condition = false;
45 /// let result = try_block!({
46 /// if (some_condition) {
47 /// bail!("some error");
51 /// .map_err(|e| format_err!("my try block returned an error - {}", e));
55 macro_rules
! try_block
{
56 { $($token:tt)* }
=> {{ (|| -> Result<_,_> { $($token)* }
)() }}
60 /// The `BufferedRead` trait provides a single function
61 /// `buffered_read`. It returns a reference to an internal buffer. The
62 /// purpose of this traid is to avoid unnecessary data copies.
63 pub trait BufferedRead
{
64 /// This functions tries to fill the internal buffers, then
65 /// returns a reference to the available data. It returns an empty
66 /// buffer if `offset` points to the end of the file.
67 fn buffered_read(&mut self, offset
: u64) -> Result
<&[u8], Error
>;
70 /// Directly map a type into a binary buffer. This is mostly useful
71 /// for reading structured data from a byte stream (file). You need to
72 /// make sure that the buffer location does not change, so please
73 /// avoid vec resize while you use such map.
75 /// This function panics if the buffer is not large enough.
76 pub fn map_struct
<T
>(buffer
: &[u8]) -> Result
<&T
, Error
> {
77 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
78 bail
!("unable to map struct - buffer too small");
80 Ok(unsafe { & * (buffer.as_ptr() as *const T) }
)
83 /// Directly map a type into a mutable binary buffer. This is mostly
84 /// useful for writing structured data into a byte stream (file). You
85 /// need to make sure that the buffer location does not change, so
86 /// please avoid vec resize while you use such map.
88 /// This function panics if the buffer is not large enough.
89 pub fn map_struct_mut
<T
>(buffer
: &mut [u8]) -> Result
<&mut T
, Error
> {
90 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
91 bail
!("unable to map struct - buffer too small");
93 Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) }
)
96 pub fn file_read_firstline
<P
: AsRef
<Path
>>(path
: P
) -> Result
<String
, Error
> {
98 let path
= path
.as_ref();
101 let file
= std
::fs
::File
::open(path
)?
;
103 use std
::io
::{BufRead, BufReader}
;
105 let mut reader
= BufReader
::new(file
);
107 let mut line
= String
::new();
109 let _
= reader
.read_line(&mut line
)?
;
112 }).map_err(|err
: Error
| format_err
!("unable to read {:?} - {}", path
, err
))
115 pub fn file_get_contents
<P
: AsRef
<Path
>>(path
: P
) -> Result
<Vec
<u8>, Error
> {
117 let path
= path
.as_ref();
121 }).map_err(|err
| format_err
!("unable to read {:?} - {}", path
, err
))
124 pub fn file_get_json
<P
: AsRef
<Path
>>(path
: P
) -> Result
<Value
, Error
> {
126 let path
= path
.as_ref();
128 let raw
= file_get_contents(path
)?
;
131 let data
= String
::from_utf8(raw
)?
;
132 let json
= serde_json
::from_str(&data
)?
;
134 }).map_err(|err
: Error
| format_err
!("unable to read json from {:?} - {}", path
, err
))
137 /// Atomically write a file. We first create a temporary file, which
139 pub fn file_set_contents
<P
: AsRef
<Path
>>(
142 perm
: Option
<stat
::Mode
>,
143 ) -> Result
<(), Error
> {
145 let path
= path
.as_ref();
147 // Note: we use mkstemp heŕe, because this worka with different
148 // processes, threads, and even tokio tasks.
149 let mut template
= path
.to_owned();
150 template
.set_extension("tmp_XXXXXX");
151 let (fd
, tmp_path
) = match unistd
::mkstemp(&template
) {
152 Ok((fd
, path
)) => (fd
, path
),
153 Err(err
) => bail
!("mkstemp {:?} failed: {}", template
, err
),
156 let tmp_path
= tmp_path
.as_path();
158 let mode
: stat
::Mode
= perm
.unwrap_or(stat
::Mode
::from(
159 stat
::Mode
::S_IRUSR
| stat
::Mode
::S_IWUSR
|
160 stat
::Mode
::S_IRGRP
| stat
::Mode
::S_IROTH
163 if let Err(err
) = stat
::fchmod(fd
, mode
) {
164 let _
= unistd
::unlink(tmp_path
);
165 bail
!("fchmod {:?} failed: {}", tmp_path
, err
);
168 use std
::os
::unix
::io
::FromRawFd
;
169 let mut file
= unsafe { File::from_raw_fd(fd) }
;
171 if let Err(err
) = file
.write_all(data
) {
172 let _
= unistd
::unlink(tmp_path
);
173 bail
!("write failed: {}", err
);
176 if let Err(err
) = std
::fs
::rename(tmp_path
, path
) {
177 let _
= unistd
::unlink(tmp_path
);
178 bail
!("Atomic rename failed for file {:?} - {}", path
, err
);
184 /// Create a file lock using fntl. This function allows you to specify
185 /// a timeout if you want to avoid infinite blocking.
186 pub fn lock_file
<F
: AsRawFd
>(
189 timeout
: Option
<Duration
>,
190 ) -> Result
<(), Error
>
194 nix
::fcntl
::FlockArg
::LockExclusive
196 nix
::fcntl
::FlockArg
::LockShared
199 let timeout
= match timeout
{
201 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
207 // unblock the timeout signal temporarily
208 let _sigblock_guard
= timer
::unblock_timeout_signal();
210 // setup a timeout timer
211 let mut timer
= timer
::Timer
::create(
212 timer
::Clock
::Realtime
,
213 timer
::TimerEvent
::ThisThreadSignal(timer
::SIGTIMEOUT
))?
;
215 timer
.arm(timer
::TimerSpec
::new()
216 .value(Some(timeout
))
217 .interval(Some(Duration
::from_millis(10))))?
;
219 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
223 /// Open or create a lock file (append mode). Then try to
224 /// aquire a lock using `lock_file()`.
225 pub fn open_file_locked
<P
: AsRef
<Path
>>(path
: P
, timeout
: Duration
)
226 -> Result
<File
, Error
>
228 let path
= path
.as_ref();
230 match OpenOptions
::new()
236 Err(err
) => bail
!("Unable to open lock {:?} - {}",
239 match lock_file(&mut file
, true, Some(timeout
)) {
241 Err(err
) => bail
!("Unable to aquire lock {:?} - {}",
246 /// Split a file into equal sized chunks. The last chunk may be
247 /// smaller. Note: We cannot implement an `Iterator`, because iterators
248 /// cannot return a borrowed buffer ref (we want zero-copy)
249 pub fn file_chunker
<C
, R
>(
253 ) -> Result
<(), Error
>
254 where C
: FnMut(usize, &[u8]) -> Result
<bool
, Error
>,
258 const READ_BUFFER_SIZE
: usize = 4*1024*1024; // 4M
260 if chunk_size
> READ_BUFFER_SIZE { bail!("chunk size too large!"); }
262 let mut buf
= vec
![0u8; READ_BUFFER_SIZE
];
265 let mut file_pos
= 0;
268 let mut tmp
= &mut buf
[..];
269 // try to read large portions, at least chunk_size
270 while pos
< chunk_size
{
271 match file
.read(tmp
) {
272 Ok(0) => { eof = true; break; }
,
275 if pos
> chunk_size { break; }
278 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> { /* try again */ }
279 Err(e
) => bail
!("read chunk failed - {}", e
.to_string()),
283 while start
+ chunk_size
<= pos
{
284 if !(chunk_cb
)(file_pos
, &buf
[start
..start
+chunk_size
])? { break; }
285 file_pos
+= chunk_size
;
290 (chunk_cb
)(file_pos
, &buf
[start
..pos
])?
;
291 //file_pos += pos - start;
295 let rest
= pos
- start
;
297 let ptr
= buf
.as_mut_ptr();
298 unsafe { std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest); }
309 // Returns the Unix uid/gid for the sepcified system user.
310 pub fn getpwnam_ugid(username
: &str) -> Result
<(libc
::uid_t
,libc
::gid_t
), Error
> {
311 let info
= unsafe { libc::getpwnam(std::ffi::CString::new(username).unwrap().as_ptr()) }
;
312 if info
== std
::ptr
::null_mut() {
313 bail
!("getwpnam '{}' failed", username
);
316 let info
= unsafe { *info }
;
318 Ok((info
.pw_uid
, info
.pw_gid
))
321 // Returns the hosts node name (UTS node name)
322 pub fn nodename() -> &'
static str {
325 static ref NODENAME
: String
= {
327 nix
::sys
::utsname
::uname()
339 pub fn json_object_to_query(data
: Value
) -> Result
<String
, Error
> {
341 let mut query
= url
::form_urlencoded
::Serializer
::new(String
::new());
343 let object
= data
.as_object().ok_or_else(|| {
344 format_err
!("json_object_to_query: got wrong data type (expected object).")
347 for (key
, value
) in object
{
349 Value
::Bool(b
) => { query.append_pair(key, &b.to_string()); }
350 Value
::Number(n
) => { query.append_pair(key, &n.to_string()); }
351 Value
::String(s
) => { query.append_pair(key, &s); }
352 Value
::Array(arr
) => {
355 Value
::Bool(b
) => { query.append_pair(key, &b.to_string()); }
356 Value
::Number(n
) => { query.append_pair(key, &n.to_string()); }
357 Value
::String(s
) => { query.append_pair(key, &s); }
358 _
=> bail
!("json_object_to_query: unable to handle complex array data types."),
362 _
=> bail
!("json_object_to_query: unable to handle complex data types."),
369 pub fn required_string_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<&'a
str, Error
> {
370 match param
[name
].as_str() {
372 None
=> bail
!("missing parameter '{}'", name
),
376 pub fn required_integer_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<i64, Error
> {
377 match param
[name
].as_i64() {
379 None
=> bail
!("missing parameter '{}'", name
),
383 pub fn required_array_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<Vec
<Value
>, Error
> {
384 match param
[name
].as_array() {
385 Some(s
) => Ok(s
.to_vec()),
386 None
=> bail
!("missing parameter '{}'", name
),
390 pub fn complete_file_name(arg
: &str, _param
: &HashMap
<String
, String
>) -> Vec
<String
> {
392 let mut result
= vec
![];
394 use nix
::fcntl
::OFlag
;
395 use nix
::sys
::stat
::Mode
;
396 use nix
::fcntl
::AtFlags
;
398 let mut dirname
= std
::path
::PathBuf
::from(if arg
.len() == 0 { "./" }
else { arg }
);
400 let is_dir
= match nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &dirname
, AtFlags
::empty()) {
401 Ok(stat
) => (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
,
406 if let Some(parent
) = dirname
.parent() {
407 dirname
= parent
.to_owned();
411 let mut dir
= match nix
::dir
::Dir
::openat(libc
::AT_FDCWD
, &dirname
, OFlag
::O_DIRECTORY
, Mode
::empty()) {
413 Err(_
) => return result
,
416 for item
in dir
.iter() {
417 if let Ok(entry
) = item
{
418 if let Ok(name
) = entry
.file_name().to_str() {
419 if name
== "." || name
== ".." { continue; }
420 let mut newpath
= dirname
.clone();
423 if let Ok(stat
) = nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &newpath
, AtFlags
::empty()) {
424 if (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
{
426 if let Some(newpath
) = newpath
.to_str() {
427 result
.push(newpath
.to_owned());
432 if let Some(newpath
) = newpath
.to_str() {
433 result
.push(newpath
.to_owned());
443 /// Scan directory for matching file names.
445 /// Scan through all directory entries and call `callback()` function
446 /// if the entry name matches the regular expression. This function
447 /// used unix `openat()`, so you can pass absolute or relative file
448 /// names. This function simply skips non-UTF8 encoded names.
449 pub fn scandir
<P
, F
>(
452 regex
: ®ex
::Regex
,
454 ) -> Result
<(), Error
>
455 where F
: FnMut(RawFd
, &str, nix
::dir
::Type
) -> Result
<(), Error
>,
456 P
: ?Sized
+ nix
::NixPath
,
458 for entry
in self::fs
::scan_subdir(dirfd
, path
, regex
)?
{
460 let file_type
= match entry
.file_type() {
461 Some(file_type
) => file_type
,
462 None
=> bail
!("unable to detect file type"),
465 callback(entry
.parent_fd(), unsafe { entry.file_name_utf8_unchecked() }
, file_type
)?
;
470 pub fn get_hardware_address() -> Result
<String
, Error
> {
472 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
474 let contents
= file_get_contents(FILENAME
)?
;
475 let digest
= md5
::compute(contents
);
477 Ok(format
!("{:0x}", digest
))
480 pub fn digest_to_hex(digest
: &[u8]) -> String
{
482 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
484 let mut buf
= Vec
::<u8>::with_capacity(digest
.len()*2);
486 for i
in 0..digest
.len() {
487 buf
.push(HEX_CHARS
[(digest
[i
] >> 4) as usize]);
488 buf
.push(HEX_CHARS
[(digest
[i
] & 0xf) as usize]);
491 unsafe { String::from_utf8_unchecked(buf) }
494 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
495 if digest1
!= digest2
{
496 bail
!("detected modified configuration - file changed by other user? Try again.");
501 /// Extract authentication cookie from cookie header.
502 /// We assume cookie_name is already url encoded.
503 pub fn extract_auth_cookie(cookie
: &str, cookie_name
: &str) -> Option
<String
> {
505 for pair
in cookie
.split('
;'
) {
507 let (name
, value
) = match pair
.find('
='
) {
508 Some(i
) => (pair
[..i
].trim(), pair
[(i
+ 1)..].trim()),
509 None
=> return None
, // Cookie format error
512 if name
== cookie_name
{
513 use url
::percent_encoding
::percent_decode
;
514 if let Ok(value
) = percent_decode(value
.as_bytes()).decode_utf8() {
515 return Some(value
.into());
517 return None
; // Cookie format error
525 pub fn join(data
: &Vec
<String
>, sep
: char) -> String
{
527 let mut list
= String
::new();
530 if list
.len() != 0 { list.push(sep); }