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
;
27 /// The `BufferedReader` trait provides a single function
28 /// `buffered_read`. It returns a reference to an internal buffer. The
29 /// purpose of this traid is to avoid unnecessary data copies.
30 pub trait BufferedReader
{
31 /// This functions tries to fill the internal buffers, then
32 /// returns a reference to the available data. It returns an empty
33 /// buffer if `offset` points to the end of the file.
34 fn buffered_read(&mut self, offset
: u64) -> Result
<&[u8], Error
>;
37 /// Directly map a type into a binary buffer. This is mostly useful
38 /// for reading structured data from a byte stream (file). You need to
39 /// make sure that the buffer location does not change, so please
40 /// avoid vec resize while you use such map.
42 /// This function panics if the buffer is not large enough.
43 pub fn map_struct
<T
>(buffer
: &[u8]) -> Result
<&T
, Error
> {
44 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
45 bail
!("unable to map struct - buffer too small");
47 Ok(unsafe { & * (buffer.as_ptr() as *const T) }
)
50 /// Directly map a type into a mutable binary buffer. This is mostly
51 /// useful for writing structured data into a byte stream (file). You
52 /// need to make sure that the buffer location does not change, so
53 /// please avoid vec resize while you use such map.
55 /// This function panics if the buffer is not large enough.
56 pub fn map_struct_mut
<T
>(buffer
: &mut [u8]) -> Result
<&mut T
, Error
> {
57 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
58 bail
!("unable to map struct - buffer too small");
60 Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) }
)
63 pub fn file_read_firstline
<P
: AsRef
<Path
>>(path
: P
) -> Result
<String
, std
::io
::Error
> {
65 let path
= path
.as_ref();
67 let file
= std
::fs
::File
::open(path
)?
;
69 use std
::io
::{BufRead, BufReader}
;
71 let mut reader
= BufReader
::new(file
);
73 let mut line
= String
::new();
75 let _
= reader
.read_line(&mut line
)?
;
80 pub fn file_get_contents
<P
: AsRef
<Path
>>(path
: P
) -> Result
<Vec
<u8>, std
::io
::Error
> {
82 let mut file
= std
::fs
::File
::open(path
)?
;
84 let mut buffer
= Vec
::new();
86 file
.read_to_end(&mut buffer
)?
;
91 /// Atomically write a file. We first create a temporary file, which
93 pub fn file_set_contents
<P
: AsRef
<Path
>>(
96 perm
: Option
<stat
::Mode
>,
97 ) -> Result
<(), Error
> {
99 let path
= path
.as_ref();
101 // Note: we use mkstemp heŕe, because this worka with different
102 // processes, threads, and even tokio tasks.
103 let mut template
= path
.to_owned();
104 template
.set_extension("tmp_XXXXXX");
105 let (fd
, tmp_path
) = match unistd
::mkstemp(&template
) {
106 Ok((fd
, path
)) => (fd
, path
),
107 Err(err
) => bail
!("mkstemp {:?} failed: {}", template
, err
),
110 let tmp_path
= tmp_path
.as_path();
112 let mode
: stat
::Mode
= perm
.unwrap_or(stat
::Mode
::from(
113 stat
::Mode
::S_IRUSR
| stat
::Mode
::S_IWUSR
|
114 stat
::Mode
::S_IRGRP
| stat
::Mode
::S_IROTH
117 if let Err(err
) = stat
::fchmod(fd
, mode
) {
118 let _
= unistd
::unlink(tmp_path
);
119 bail
!("fchmod {:?} failed: {}", tmp_path
, err
);
122 use std
::os
::unix
::io
::FromRawFd
;
123 let mut file
= unsafe { File::from_raw_fd(fd) }
;
125 if let Err(err
) = file
.write_all(data
) {
126 let _
= unistd
::unlink(tmp_path
);
127 bail
!("write failed: {}", err
);
130 if let Err(err
) = std
::fs
::rename(tmp_path
, path
) {
131 let _
= unistd
::unlink(tmp_path
);
132 bail
!("Atomic rename failed for file {:?} - {}", path
, err
);
138 /// Create a file lock using fntl. This function allows you to specify
139 /// a timeout if you want to avoid infinite blocking.
140 pub fn lock_file
<F
: AsRawFd
>(
143 timeout
: Option
<Duration
>,
144 ) -> Result
<(), Error
>
148 nix
::fcntl
::FlockArg
::LockExclusive
150 nix
::fcntl
::FlockArg
::LockShared
153 let timeout
= match timeout
{
155 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
161 // unblock the timeout signal temporarily
162 let _sigblock_guard
= timer
::unblock_timeout_signal();
164 // setup a timeout timer
165 let mut timer
= timer
::Timer
::create(
166 timer
::Clock
::Realtime
,
167 timer
::TimerEvent
::ThisThreadSignal(timer
::SIGTIMEOUT
))?
;
169 timer
.arm(timer
::TimerSpec
::new()
170 .value(Some(timeout
))
171 .interval(Some(Duration
::from_millis(10))))?
;
173 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
177 /// Open or create a lock file (append mode). Then try to
178 /// aquire a lock using `lock_file()`.
179 pub fn open_file_locked
<P
: AsRef
<Path
>>(path
: P
, timeout
: Duration
)
180 -> Result
<File
, Error
>
182 let path
= path
.as_ref();
184 match OpenOptions
::new()
190 Err(err
) => bail
!("Unable to open lock {:?} - {}",
193 match lock_file(&mut file
, true, Some(timeout
)) {
195 Err(err
) => bail
!("Unable to aquire lock {:?} - {}",
200 /// Split a file into equal sized chunks. The last chunk may be
201 /// smaller. Note: We cannot implement an `Iterator`, because iterators
202 /// cannot return a borrowed buffer ref (we want zero-copy)
203 pub fn file_chunker
<C
, R
>(
207 ) -> Result
<(), Error
>
208 where C
: FnMut(usize, &[u8]) -> Result
<bool
, Error
>,
212 const READ_BUFFER_SIZE
: usize = 4*1024*1024; // 4M
214 if chunk_size
> READ_BUFFER_SIZE { bail!("chunk size too large!"); }
216 let mut buf
= vec
![0u8; READ_BUFFER_SIZE
];
219 let mut file_pos
= 0;
222 let mut tmp
= &mut buf
[..];
223 // try to read large portions, at least chunk_size
224 while pos
< chunk_size
{
225 match file
.read(tmp
) {
226 Ok(0) => { eof = true; break; }
,
229 if pos
> chunk_size { break; }
232 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> { /* try again */ }
233 Err(e
) => bail
!("read chunk failed - {}", e
.to_string()),
237 while start
+ chunk_size
<= pos
{
238 if !(chunk_cb
)(file_pos
, &buf
[start
..start
+chunk_size
])? { break; }
239 file_pos
+= chunk_size
;
244 (chunk_cb
)(file_pos
, &buf
[start
..pos
])?
;
245 //file_pos += pos - start;
249 let rest
= pos
- start
;
251 let ptr
= buf
.as_mut_ptr();
252 unsafe { std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest); }
263 /// Returns the hosts node name (UTS node name)
264 pub fn nodename() -> &'
static str {
267 static ref NODENAME
: String
= {
269 nix
::sys
::utsname
::uname()
281 pub fn required_string_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<&'a
str, Error
> {
282 match param
[name
].as_str() {
284 None
=> bail
!("missing parameter '{}'", name
),
288 pub fn required_integer_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<i64, Error
> {
289 match param
[name
].as_i64() {
291 None
=> bail
!("missing parameter '{}'", name
),
295 pub fn complete_file_name(arg
: &str) -> Vec
<String
> {
297 let mut result
= vec
![];
299 use nix
::fcntl
::OFlag
;
300 use nix
::sys
::stat
::Mode
;
301 use nix
::fcntl
::AtFlags
;
303 let mut dirname
= std
::path
::PathBuf
::from(arg
);
305 let is_dir
= match nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &dirname
, AtFlags
::empty()) {
306 Ok(stat
) => (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
,
311 if let Some(parent
) = dirname
.parent() {
312 dirname
= parent
.to_owned();
316 let mut dir
= match nix
::dir
::Dir
::openat(libc
::AT_FDCWD
, &dirname
, OFlag
::O_DIRECTORY
, Mode
::empty()) {
318 Err(_
) => return result
,
321 for item
in dir
.iter() {
322 if let Ok(entry
) = item
{
323 if let Ok(name
) = entry
.file_name().to_str() {
324 if name
== "." || name
== ".." { continue; }
325 let mut newpath
= dirname
.clone();
328 if let Ok(stat
) = nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &newpath
, AtFlags
::empty()) {
329 if (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
{
331 if let Some(newpath
) = newpath
.to_str() {
332 result
.push(newpath
.to_owned());
337 if let Some(newpath
) = newpath
.to_str() {
338 result
.push(newpath
.to_owned());
348 /// Scan directory for matching file names.
350 /// Scan through all directory entries and call `callback()` function
351 /// if the entry name matches the regular expression. This function
352 /// used unix `openat()`, so you can pass absolute or relative file
353 /// names. This function simply skips non-UTF8 encoded names.
354 pub fn scandir
<P
, F
>(
357 regex
: ®ex
::Regex
,
359 ) -> Result
<(), Error
>
360 where F
: FnMut(RawFd
, &str, nix
::dir
::Type
) -> Result
<(), Error
>,
363 use nix
::fcntl
::OFlag
;
364 use nix
::sys
::stat
::Mode
;
366 let mut subdir
= nix
::dir
::Dir
::openat(dirfd
, path
.as_ref(), OFlag
::O_RDONLY
, Mode
::empty())?
;
367 let subdir_fd
= subdir
.as_raw_fd();
369 for entry
in subdir
.iter() {
371 let file_type
= match entry
.file_type() {
372 Some(file_type
) => file_type
,
373 None
=> bail
!("unable to detect file type"),
375 let filename
= entry
.file_name();
376 let filename_str
= match filename
.to_str() {
378 Err(_
) => continue /* ignore non utf8 entries*/,
381 if !regex
.is_match(filename_str
) { continue; }
383 (callback
)(subdir_fd
, filename_str
, file_type
)?
;
388 pub fn get_hardware_address() -> Result
<String
, Error
> {
390 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
392 let contents
= file_get_contents(FILENAME
)?
;
393 let digest
= md5
::compute(contents
);
395 Ok(format
!("{:0x}", digest
))
398 pub fn digest_to_hex(digest
: &[u8]) -> String
{
400 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
402 let mut buf
= Vec
::<u8>::with_capacity(digest
.len()*2);
404 for i
in 0..digest
.len() {
405 buf
.push(HEX_CHARS
[(digest
[i
] >> 4) as usize]);
406 buf
.push(HEX_CHARS
[(digest
[i
] & 0xf) as usize]);
409 unsafe { String::from_utf8_unchecked(buf) }
412 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
413 if digest1
!= digest2
{
414 bail
!("detected modified configuration - file changed by other user? Try again.");