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 serde_json
::Value
;
23 pub mod wrapped_reader_stream
;
31 /// Macro to write error-handling blocks (like perl eval {})
35 /// # #[macro_use] extern crate proxmox_backup;
37 /// # let some_condition = false;
38 /// let result = try_block!({
39 /// if (some_condition) {
40 /// bail!("some error");
44 /// .map_err(|e| format_err!("my try block returned an error - {}", e));
48 macro_rules
! try_block
{
49 { $($token:tt)* }
=> {{ (|| -> Result<_,_> { $($token)* }
)() }}
53 /// The `BufferedReader` trait provides a single function
54 /// `buffered_read`. It returns a reference to an internal buffer. The
55 /// purpose of this traid is to avoid unnecessary data copies.
56 pub trait BufferedReader
{
57 /// This functions tries to fill the internal buffers, then
58 /// returns a reference to the available data. It returns an empty
59 /// buffer if `offset` points to the end of the file.
60 fn buffered_read(&mut self, offset
: u64) -> Result
<&[u8], Error
>;
63 /// Directly map a type into a binary buffer. This is mostly useful
64 /// for reading structured data from a byte stream (file). You need to
65 /// make sure that the buffer location does not change, so please
66 /// avoid vec resize while you use such map.
68 /// This function panics if the buffer is not large enough.
69 pub fn map_struct
<T
>(buffer
: &[u8]) -> Result
<&T
, Error
> {
70 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
71 bail
!("unable to map struct - buffer too small");
73 Ok(unsafe { & * (buffer.as_ptr() as *const T) }
)
76 /// Directly map a type into a mutable binary buffer. This is mostly
77 /// useful for writing structured data into a byte stream (file). You
78 /// need to make sure that the buffer location does not change, so
79 /// please avoid vec resize while you use such map.
81 /// This function panics if the buffer is not large enough.
82 pub fn map_struct_mut
<T
>(buffer
: &mut [u8]) -> Result
<&mut T
, Error
> {
83 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
84 bail
!("unable to map struct - buffer too small");
86 Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) }
)
89 pub fn file_read_firstline
<P
: AsRef
<Path
>>(path
: P
) -> Result
<String
, Error
> {
91 let path
= path
.as_ref();
94 let file
= std
::fs
::File
::open(path
)?
;
96 use std
::io
::{BufRead, BufReader}
;
98 let mut reader
= BufReader
::new(file
);
100 let mut line
= String
::new();
102 let _
= reader
.read_line(&mut line
)?
;
105 }).map_err(|err
: Error
| format_err
!("unable to read {:?} - {}", path
, err
))
108 pub fn file_get_contents
<P
: AsRef
<Path
>>(path
: P
) -> Result
<Vec
<u8>, Error
> {
110 let path
= path
.as_ref();
114 }).map_err(|err
| format_err
!("unable to read {:?} - {}", path
, err
))
117 /// Atomically write a file. We first create a temporary file, which
119 pub fn file_set_contents
<P
: AsRef
<Path
>>(
122 perm
: Option
<stat
::Mode
>,
123 ) -> Result
<(), Error
> {
125 let path
= path
.as_ref();
127 // Note: we use mkstemp heŕe, because this worka with different
128 // processes, threads, and even tokio tasks.
129 let mut template
= path
.to_owned();
130 template
.set_extension("tmp_XXXXXX");
131 let (fd
, tmp_path
) = match unistd
::mkstemp(&template
) {
132 Ok((fd
, path
)) => (fd
, path
),
133 Err(err
) => bail
!("mkstemp {:?} failed: {}", template
, err
),
136 let tmp_path
= tmp_path
.as_path();
138 let mode
: stat
::Mode
= perm
.unwrap_or(stat
::Mode
::from(
139 stat
::Mode
::S_IRUSR
| stat
::Mode
::S_IWUSR
|
140 stat
::Mode
::S_IRGRP
| stat
::Mode
::S_IROTH
143 if let Err(err
) = stat
::fchmod(fd
, mode
) {
144 let _
= unistd
::unlink(tmp_path
);
145 bail
!("fchmod {:?} failed: {}", tmp_path
, err
);
148 use std
::os
::unix
::io
::FromRawFd
;
149 let mut file
= unsafe { File::from_raw_fd(fd) }
;
151 if let Err(err
) = file
.write_all(data
) {
152 let _
= unistd
::unlink(tmp_path
);
153 bail
!("write failed: {}", err
);
156 if let Err(err
) = std
::fs
::rename(tmp_path
, path
) {
157 let _
= unistd
::unlink(tmp_path
);
158 bail
!("Atomic rename failed for file {:?} - {}", path
, err
);
164 /// Create a file lock using fntl. This function allows you to specify
165 /// a timeout if you want to avoid infinite blocking.
166 pub fn lock_file
<F
: AsRawFd
>(
169 timeout
: Option
<Duration
>,
170 ) -> Result
<(), Error
>
174 nix
::fcntl
::FlockArg
::LockExclusive
176 nix
::fcntl
::FlockArg
::LockShared
179 let timeout
= match timeout
{
181 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
187 // unblock the timeout signal temporarily
188 let _sigblock_guard
= timer
::unblock_timeout_signal();
190 // setup a timeout timer
191 let mut timer
= timer
::Timer
::create(
192 timer
::Clock
::Realtime
,
193 timer
::TimerEvent
::ThisThreadSignal(timer
::SIGTIMEOUT
))?
;
195 timer
.arm(timer
::TimerSpec
::new()
196 .value(Some(timeout
))
197 .interval(Some(Duration
::from_millis(10))))?
;
199 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
203 /// Open or create a lock file (append mode). Then try to
204 /// aquire a lock using `lock_file()`.
205 pub fn open_file_locked
<P
: AsRef
<Path
>>(path
: P
, timeout
: Duration
)
206 -> Result
<File
, Error
>
208 let path
= path
.as_ref();
210 match OpenOptions
::new()
216 Err(err
) => bail
!("Unable to open lock {:?} - {}",
219 match lock_file(&mut file
, true, Some(timeout
)) {
221 Err(err
) => bail
!("Unable to aquire lock {:?} - {}",
226 /// Split a file into equal sized chunks. The last chunk may be
227 /// smaller. Note: We cannot implement an `Iterator`, because iterators
228 /// cannot return a borrowed buffer ref (we want zero-copy)
229 pub fn file_chunker
<C
, R
>(
233 ) -> Result
<(), Error
>
234 where C
: FnMut(usize, &[u8]) -> Result
<bool
, Error
>,
238 const READ_BUFFER_SIZE
: usize = 4*1024*1024; // 4M
240 if chunk_size
> READ_BUFFER_SIZE { bail!("chunk size too large!"); }
242 let mut buf
= vec
![0u8; READ_BUFFER_SIZE
];
245 let mut file_pos
= 0;
248 let mut tmp
= &mut buf
[..];
249 // try to read large portions, at least chunk_size
250 while pos
< chunk_size
{
251 match file
.read(tmp
) {
252 Ok(0) => { eof = true; break; }
,
255 if pos
> chunk_size { break; }
258 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> { /* try again */ }
259 Err(e
) => bail
!("read chunk failed - {}", e
.to_string()),
263 while start
+ chunk_size
<= pos
{
264 if !(chunk_cb
)(file_pos
, &buf
[start
..start
+chunk_size
])? { break; }
265 file_pos
+= chunk_size
;
270 (chunk_cb
)(file_pos
, &buf
[start
..pos
])?
;
271 //file_pos += pos - start;
275 let rest
= pos
- start
;
277 let ptr
= buf
.as_mut_ptr();
278 unsafe { std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest); }
289 // Returns the Unix uid/gid for the sepcified system user.
290 pub fn getpwnam_ugid(username
: &str) -> Result
<(libc
::uid_t
,libc
::gid_t
), Error
> {
291 let info
= unsafe { libc::getpwnam(std::ffi::CString::new(username).unwrap().as_ptr()) }
;
292 if info
== std
::ptr
::null_mut() {
293 bail
!("getwpnam '{}' failed", username
);
296 let info
= unsafe { *info }
;
298 Ok((info
.pw_uid
, info
.pw_gid
))
301 // Returns the hosts node name (UTS node name)
302 pub fn nodename() -> &'
static str {
305 static ref NODENAME
: String
= {
307 nix
::sys
::utsname
::uname()
319 pub fn required_string_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<&'a
str, Error
> {
320 match param
[name
].as_str() {
322 None
=> bail
!("missing parameter '{}'", name
),
326 pub fn required_integer_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<i64, Error
> {
327 match param
[name
].as_i64() {
329 None
=> bail
!("missing parameter '{}'", name
),
333 pub fn complete_file_name(arg
: &str) -> Vec
<String
> {
335 let mut result
= vec
![];
337 use nix
::fcntl
::OFlag
;
338 use nix
::sys
::stat
::Mode
;
339 use nix
::fcntl
::AtFlags
;
341 let mut dirname
= std
::path
::PathBuf
::from(arg
);
343 let is_dir
= match nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &dirname
, AtFlags
::empty()) {
344 Ok(stat
) => (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
,
349 if let Some(parent
) = dirname
.parent() {
350 dirname
= parent
.to_owned();
354 let mut dir
= match nix
::dir
::Dir
::openat(libc
::AT_FDCWD
, &dirname
, OFlag
::O_DIRECTORY
, Mode
::empty()) {
356 Err(_
) => return result
,
359 for item
in dir
.iter() {
360 if let Ok(entry
) = item
{
361 if let Ok(name
) = entry
.file_name().to_str() {
362 if name
== "." || name
== ".." { continue; }
363 let mut newpath
= dirname
.clone();
366 if let Ok(stat
) = nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &newpath
, AtFlags
::empty()) {
367 if (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
{
369 if let Some(newpath
) = newpath
.to_str() {
370 result
.push(newpath
.to_owned());
375 if let Some(newpath
) = newpath
.to_str() {
376 result
.push(newpath
.to_owned());
386 /// Scan directory for matching file names.
388 /// Scan through all directory entries and call `callback()` function
389 /// if the entry name matches the regular expression. This function
390 /// used unix `openat()`, so you can pass absolute or relative file
391 /// names. This function simply skips non-UTF8 encoded names.
392 pub fn scandir
<P
, F
>(
395 regex
: ®ex
::Regex
,
397 ) -> Result
<(), Error
>
398 where F
: FnMut(RawFd
, &str, nix
::dir
::Type
) -> Result
<(), Error
>,
399 P
: ?Sized
+ nix
::NixPath
,
401 for entry
in self::fs
::scan_subdir(dirfd
, path
, regex
)?
{
403 let file_type
= match entry
.file_type() {
404 Some(file_type
) => file_type
,
405 None
=> bail
!("unable to detect file type"),
408 callback(entry
.parent_fd(), unsafe { entry.file_name_utf8_unchecked() }
, file_type
)?
;
413 pub fn get_hardware_address() -> Result
<String
, Error
> {
415 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
417 let contents
= file_get_contents(FILENAME
)?
;
418 let digest
= md5
::compute(contents
);
420 Ok(format
!("{:0x}", digest
))
423 pub fn digest_to_hex(digest
: &[u8]) -> String
{
425 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
427 let mut buf
= Vec
::<u8>::with_capacity(digest
.len()*2);
429 for i
in 0..digest
.len() {
430 buf
.push(HEX_CHARS
[(digest
[i
] >> 4) as usize]);
431 buf
.push(HEX_CHARS
[(digest
[i
] & 0xf) as usize]);
434 unsafe { String::from_utf8_unchecked(buf) }
437 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
438 if digest1
!= digest2
{
439 bail
!("detected modified configuration - file changed by other user? Try again.");
444 /// Extract authentication cookie from cookie header.
445 /// We assume cookie_name is already url encoded.
446 pub fn extract_auth_cookie(cookie
: &str, cookie_name
: &str) -> Option
<String
> {
448 for pair
in cookie
.split('
;'
) {
450 let (name
, value
) = match pair
.find('
='
) {
451 Some(i
) => (pair
[..i
].trim(), pair
[(i
+ 1)..].trim()),
452 None
=> return None
, // Cookie format error
455 if name
== cookie_name
{
456 use url
::percent_encoding
::percent_decode
;
457 if let Ok(value
) = percent_decode(value
.as_bytes()).decode_utf8() {
458 return Some(value
.into());
460 return None
; // Cookie format error