]> git.proxmox.com Git - proxmox-backup.git/blame - src/tools.rs
allow(clippy::cast_ptr_alignment)
[proxmox-backup.git] / src / tools.rs
CommitLineData
51b499db
DM
1//! Tools and utilities
2//!
3//! This is a collection of small and useful tools.
6100071f
WB
4use std::any::Any;
5use std::collections::HashMap;
365bb90f 6use std::fs::{File, OpenOptions};
43eeef28 7use std::io::ErrorKind;
6100071f 8use std::io::Read;
d96bb7f1 9use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
6100071f
WB
10use std::path::Path;
11use std::time::Duration;
365bb90f 12
6100071f 13use failure::*;
af926291 14use serde_json::Value;
0fe5d605 15
f35197f4
WB
16use proxmox::tools::vec;
17
6100071f 18pub mod acl;
556eb70e 19pub mod async_io;
d82ed9b0 20pub mod async_mutex;
6ed25cbe 21pub mod borrow;
6100071f 22pub mod daemon;
b4d5787d 23pub mod fs;
6100071f 24pub mod futures;
daef93f4 25pub mod runtime;
6100071f
WB
26pub mod ticket;
27pub mod timer;
28pub mod tty;
29pub mod wrapped_reader_stream;
2dcdd3b4 30pub mod xattr;
8cf6e764 31
a650f503
DM
32mod process_locker;
33pub use process_locker::*;
34
3b151414
DM
35mod file_logger;
36pub use file_logger::*;
37
490be29e
DM
38mod broadcast_future;
39pub use broadcast_future::*;
40
fded74d0 41/// The `BufferedRead` trait provides a single function
0a72e267
DM
42/// `buffered_read`. It returns a reference to an internal buffer. The
43/// purpose of this traid is to avoid unnecessary data copies.
fded74d0 44pub trait BufferedRead {
318564ac
DM
45 /// This functions tries to fill the internal buffers, then
46 /// returns a reference to the available data. It returns an empty
47 /// buffer if `offset` points to the end of the file.
0a72e267
DM
48 fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>;
49}
50
51b499db
DM
51/// Directly map a type into a binary buffer. This is mostly useful
52/// for reading structured data from a byte stream (file). You need to
53/// make sure that the buffer location does not change, so please
54/// avoid vec resize while you use such map.
55///
56/// This function panics if the buffer is not large enough.
50ea4396 57pub fn map_struct<T>(buffer: &[u8]) -> Result<&T, Error> {
dc3de618
DM
58 if buffer.len() < ::std::mem::size_of::<T>() {
59 bail!("unable to map struct - buffer too small");
60 }
6100071f 61 Ok(unsafe { &*(buffer.as_ptr() as *const T) })
dc3de618
DM
62}
63
51b499db
DM
64/// Directly map a type into a mutable binary buffer. This is mostly
65/// useful for writing structured data into a byte stream (file). You
66/// need to make sure that the buffer location does not change, so
67/// please avoid vec resize while you use such map.
68///
69/// This function panics if the buffer is not large enough.
50ea4396 70pub fn map_struct_mut<T>(buffer: &mut [u8]) -> Result<&mut T, Error> {
dc3de618
DM
71 if buffer.len() < ::std::mem::size_of::<T>() {
72 bail!("unable to map struct - buffer too small");
73 }
6100071f 74 Ok(unsafe { &mut *(buffer.as_ptr() as *mut T) })
dc3de618
DM
75}
76
51b499db
DM
77/// Create a file lock using fntl. This function allows you to specify
78/// a timeout if you want to avoid infinite blocking.
1628a4c7
WB
79pub fn lock_file<F: AsRawFd>(
80 file: &mut F,
81 exclusive: bool,
82 timeout: Option<Duration>,
eb90c9e3 83) -> Result<(), Error> {
6100071f
WB
84 let lockarg = if exclusive {
85 nix::fcntl::FlockArg::LockExclusive
86 } else {
87 nix::fcntl::FlockArg::LockShared
88 };
1628a4c7
WB
89
90 let timeout = match timeout {
91 None => {
92 nix::fcntl::flock(file.as_raw_fd(), lockarg)?;
93 return Ok(());
94 }
95 Some(t) => t,
96 };
97
98 // unblock the timeout signal temporarily
99 let _sigblock_guard = timer::unblock_timeout_signal();
100
101 // setup a timeout timer
102 let mut timer = timer::Timer::create(
103 timer::Clock::Realtime,
6100071f
WB
104 timer::TimerEvent::ThisThreadSignal(timer::SIGTIMEOUT),
105 )?;
1628a4c7 106
6100071f
WB
107 timer.arm(
108 timer::TimerSpec::new()
109 .value(Some(timeout))
110 .interval(Some(Duration::from_millis(10))),
111 )?;
1628a4c7
WB
112
113 nix::fcntl::flock(file.as_raw_fd(), lockarg)?;
114 Ok(())
115}
365bb90f 116
51b499db
DM
117/// Open or create a lock file (append mode). Then try to
118/// aquire a lock using `lock_file()`.
6100071f 119pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<File, Error> {
1628a4c7 120 let path = path.as_ref();
6100071f
WB
121 let mut file = match OpenOptions::new().create(true).append(true).open(path) {
122 Ok(file) => file,
123 Err(err) => bail!("Unable to open lock {:?} - {}", path, err),
124 };
28b96b56
DM
125 match lock_file(&mut file, true, Some(timeout)) {
126 Ok(_) => Ok(file),
6100071f 127 Err(err) => bail!("Unable to aquire lock {:?} - {}", path, err),
28b96b56 128 }
365bb90f
DM
129}
130
51b499db
DM
131/// Split a file into equal sized chunks. The last chunk may be
132/// smaller. Note: We cannot implement an `Iterator`, because iterators
133/// cannot return a borrowed buffer ref (we want zero-copy)
6100071f
WB
134pub fn file_chunker<C, R>(mut file: R, chunk_size: usize, mut chunk_cb: C) -> Result<(), Error>
135where
136 C: FnMut(usize, &[u8]) -> Result<bool, Error>,
137 R: Read,
43eeef28 138{
6100071f 139 const READ_BUFFER_SIZE: usize = 4 * 1024 * 1024; // 4M
43eeef28 140
6100071f
WB
141 if chunk_size > READ_BUFFER_SIZE {
142 bail!("chunk size too large!");
143 }
43eeef28 144
8ea3b1d1 145 let mut buf = vec::undefined(READ_BUFFER_SIZE);
43eeef28
DM
146
147 let mut pos = 0;
148 let mut file_pos = 0;
149 loop {
150 let mut eof = false;
151 let mut tmp = &mut buf[..];
6100071f 152 // try to read large portions, at least chunk_size
43eeef28
DM
153 while pos < chunk_size {
154 match file.read(tmp) {
6100071f
WB
155 Ok(0) => {
156 eof = true;
157 break;
158 }
43eeef28
DM
159 Ok(n) => {
160 pos += n;
6100071f
WB
161 if pos > chunk_size {
162 break;
163 }
43eeef28
DM
164 tmp = &mut tmp[n..];
165 }
166 Err(ref e) if e.kind() == ErrorKind::Interrupted => { /* try again */ }
5f0c2d56 167 Err(e) => bail!("read chunk failed - {}", e.to_string()),
43eeef28
DM
168 }
169 }
43eeef28
DM
170 let mut start = 0;
171 while start + chunk_size <= pos {
6100071f
WB
172 if !(chunk_cb)(file_pos, &buf[start..start + chunk_size])? {
173 break;
174 }
43eeef28
DM
175 file_pos += chunk_size;
176 start += chunk_size;
177 }
178 if eof {
179 if start < pos {
180 (chunk_cb)(file_pos, &buf[start..pos])?;
181 //file_pos += pos - start;
182 }
183 break;
184 } else {
185 let rest = pos - start;
186 if rest > 0 {
187 let ptr = buf.as_mut_ptr();
6100071f
WB
188 unsafe {
189 std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest);
190 }
43eeef28
DM
191 pos = rest;
192 } else {
193 pos = 0;
194 }
195 }
196 }
197
198 Ok(())
43eeef28 199}
0fe5d605 200
eea81319 201/// Returns the Unix uid/gid for the sepcified system user.
6100071f 202pub fn getpwnam_ugid(username: &str) -> Result<(libc::uid_t, libc::gid_t), Error> {
299a2f18
WB
203 let c_username = std::ffi::CString::new(username).unwrap();
204 let info = unsafe { libc::getpwnam(c_username.as_ptr()) };
5d14eb6a
DM
205 if info == std::ptr::null_mut() {
206 bail!("getwpnam '{}' failed", username);
207 }
208
209 let info = unsafe { *info };
210
211 Ok((info.pw_uid, info.pw_gid))
212}
213
f5f13ebc 214pub fn json_object_to_query(data: Value) -> Result<String, Error> {
f5f13ebc
DM
215 let mut query = url::form_urlencoded::Serializer::new(String::new());
216
217 let object = data.as_object().ok_or_else(|| {
218 format_err!("json_object_to_query: got wrong data type (expected object).")
219 })?;
220
221 for (key, value) in object {
222 match value {
6100071f
WB
223 Value::Bool(b) => {
224 query.append_pair(key, &b.to_string());
225 }
226 Value::Number(n) => {
227 query.append_pair(key, &n.to_string());
228 }
229 Value::String(s) => {
230 query.append_pair(key, &s);
231 }
f5f13ebc
DM
232 Value::Array(arr) => {
233 for element in arr {
234 match element {
6100071f
WB
235 Value::Bool(b) => {
236 query.append_pair(key, &b.to_string());
237 }
238 Value::Number(n) => {
239 query.append_pair(key, &n.to_string());
240 }
241 Value::String(s) => {
242 query.append_pair(key, &s);
243 }
244 _ => bail!(
245 "json_object_to_query: unable to handle complex array data types."
246 ),
f5f13ebc
DM
247 }
248 }
249 }
250 _ => bail!("json_object_to_query: unable to handle complex data types."),
251 }
252 }
253
254 Ok(query.finish())
255}
256
0fe5d605 257pub fn required_string_param<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> {
6100071f 258 match param[name].as_str() {
0fe5d605
DM
259 Some(s) => Ok(s),
260 None => bail!("missing parameter '{}'", name),
261 }
262}
0d38dcb4 263
e17d5d86
DM
264pub fn required_string_property<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> {
265 match param[name].as_str() {
266 Some(s) => Ok(s),
267 None => bail!("missing property '{}'", name),
268 }
269}
270
0d38dcb4 271pub fn required_integer_param<'a>(param: &'a Value, name: &str) -> Result<i64, Error> {
6100071f 272 match param[name].as_i64() {
0d38dcb4
DM
273 Some(s) => Ok(s),
274 None => bail!("missing parameter '{}'", name),
f8dfbb45
DM
275 }
276}
277
e17d5d86
DM
278pub fn required_integer_property<'a>(param: &'a Value, name: &str) -> Result<i64, Error> {
279 match param[name].as_i64() {
280 Some(s) => Ok(s),
281 None => bail!("missing property '{}'", name),
282 }
283}
284
f8dfbb45 285pub fn required_array_param<'a>(param: &'a Value, name: &str) -> Result<Vec<Value>, Error> {
6100071f 286 match param[name].as_array() {
f8dfbb45
DM
287 Some(s) => Ok(s.to_vec()),
288 None => bail!("missing parameter '{}'", name),
0d38dcb4
DM
289 }
290}
383e8577 291
e17d5d86
DM
292pub fn required_array_property<'a>(param: &'a Value, name: &str) -> Result<Vec<Value>, Error> {
293 match param[name].as_array() {
294 Some(s) => Ok(s.to_vec()),
295 None => bail!("missing property '{}'", name),
296 }
297}
298
496a6784 299pub fn complete_file_name(arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
383e8577
DM
300 let mut result = vec![];
301
6100071f 302 use nix::fcntl::AtFlags;
383e8577
DM
303 use nix::fcntl::OFlag;
304 use nix::sys::stat::Mode;
383e8577 305
806500cd 306 let mut dirname = std::path::PathBuf::from(if arg.len() == 0 { "./" } else { arg });
383e8577
DM
307
308 let is_dir = match nix::sys::stat::fstatat(libc::AT_FDCWD, &dirname, AtFlags::empty()) {
309 Ok(stat) => (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR,
310 Err(_) => false,
311 };
312
313 if !is_dir {
314 if let Some(parent) = dirname.parent() {
315 dirname = parent.to_owned();
316 }
317 }
318
6100071f
WB
319 let mut dir =
320 match nix::dir::Dir::openat(libc::AT_FDCWD, &dirname, OFlag::O_DIRECTORY, Mode::empty()) {
321 Ok(d) => d,
322 Err(_) => return result,
323 };
383e8577
DM
324
325 for item in dir.iter() {
326 if let Ok(entry) = item {
327 if let Ok(name) = entry.file_name().to_str() {
6100071f
WB
328 if name == "." || name == ".." {
329 continue;
330 }
383e8577
DM
331 let mut newpath = dirname.clone();
332 newpath.push(name);
333
6100071f
WB
334 if let Ok(stat) =
335 nix::sys::stat::fstatat(libc::AT_FDCWD, &newpath, AtFlags::empty())
336 {
383e8577
DM
337 if (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR {
338 newpath.push("");
339 if let Some(newpath) = newpath.to_str() {
340 result.push(newpath.to_owned());
341 }
342 continue;
6100071f 343 }
383e8577
DM
344 }
345 if let Some(newpath) = newpath.to_str() {
346 result.push(newpath.to_owned());
347 }
6100071f 348 }
383e8577
DM
349 }
350 }
351
352 result
353}
443f3743
DM
354
355/// Scan directory for matching file names.
356///
357/// Scan through all directory entries and call `callback()` function
358/// if the entry name matches the regular expression. This function
359/// used unix `openat()`, so you can pass absolute or relative file
360/// names. This function simply skips non-UTF8 encoded names.
361pub fn scandir<P, F>(
362 dirfd: RawFd,
121f18ef 363 path: &P,
443f3743 364 regex: &regex::Regex,
6100071f 365 mut callback: F,
443f3743 366) -> Result<(), Error>
6100071f
WB
367where
368 F: FnMut(RawFd, &str, nix::dir::Type) -> Result<(), Error>,
369 P: ?Sized + nix::NixPath,
443f3743 370{
121f18ef 371 for entry in self::fs::scan_subdir(dirfd, path, regex)? {
443f3743
DM
372 let entry = entry?;
373 let file_type = match entry.file_type() {
374 Some(file_type) => file_type,
375 None => bail!("unable to detect file type"),
376 };
443f3743 377
6100071f
WB
378 callback(
379 entry.parent_fd(),
380 unsafe { entry.file_name_utf8_unchecked() },
381 file_type,
382 )?;
443f3743
DM
383 }
384 Ok(())
385}
7e13b2d6
DM
386
387pub fn get_hardware_address() -> Result<String, Error> {
1631c54f 388 static FILENAME: &str = "/etc/ssh/ssh_host_rsa_key.pub";
7e13b2d6 389
e18a6c9e 390 let contents = proxmox::tools::fs::file_get_contents(FILENAME)?;
7e13b2d6
DM
391 let digest = md5::compute(contents);
392
393 Ok(format!("{:0x}", digest))
394}
22968600 395
af2fddea
DM
396pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> {
397 if digest1 != digest2 {
6100071f 398 bail!("detected modified configuration - file changed by other user? Try again.");
af2fddea
DM
399 }
400 Ok(())
401}
b9903d63
DM
402
403/// Extract authentication cookie from cookie header.
404/// We assume cookie_name is already url encoded.
405pub fn extract_auth_cookie(cookie: &str, cookie_name: &str) -> Option<String> {
b9903d63 406 for pair in cookie.split(';') {
b9903d63
DM
407 let (name, value) = match pair.find('=') {
408 Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()),
409 None => return None, // Cookie format error
410 };
411
412 if name == cookie_name {
413 use url::percent_encoding::percent_decode;
414 if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() {
415 return Some(value.into());
416 } else {
417 return None; // Cookie format error
418 }
419 }
420 }
421
422 None
423}
af53186e
DM
424
425pub fn join(data: &Vec<String>, sep: char) -> String {
af53186e
DM
426 let mut list = String::new();
427
428 for item in data {
6100071f
WB
429 if list.len() != 0 {
430 list.push(sep);
431 }
af53186e
DM
432 list.push_str(item);
433 }
434
435 list
436}
ff7049d4 437
3578d99f
DM
438/// normalize uri path
439///
440/// Do not allow ".", "..", or hidden files ".XXXX"
441/// Also remove empty path components
442pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> {
3578d99f
DM
443 let items = path.split('/');
444
445 let mut path = String::new();
446 let mut components = vec![];
447
448 for name in items {
6100071f
WB
449 if name.is_empty() {
450 continue;
451 }
3578d99f
DM
452 if name.starts_with(".") {
453 bail!("Path contains illegal components.");
454 }
455 path.push('/');
456 path.push_str(name);
457 components.push(name);
458 }
459
460 Ok((path, components))
461}
462
ff7049d4 463pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> {
6100071f 464 use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD};
ff7049d4
WB
465 let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?)
466 .ok_or_else(|| format_err!("unhandled file flags"))?; // nix crate is stupid this way...
467 flags.set(FdFlag::FD_CLOEXEC, on);
468 fcntl(fd, F_SETFD(flags))?;
469 Ok(())
470}
9136f857 471
9136f857
DM
472static mut SHUTDOWN_REQUESTED: bool = false;
473
474pub fn request_shutdown() {
6100071f
WB
475 unsafe {
476 SHUTDOWN_REQUESTED = true;
477 }
7a630df7 478 crate::server::server_shutdown();
9136f857
DM
479}
480
481#[inline(always)]
482pub fn shutdown_requested() -> bool {
483 unsafe { SHUTDOWN_REQUESTED }
484}
92da93b2
DM
485
486pub fn fail_on_shutdown() -> Result<(), Error> {
487 if shutdown_requested() {
488 bail!("Server shutdown requested - aborting task");
489 }
490 Ok(())
491}
d96bb7f1
WB
492
493/// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
494/// `RawFd` is required without the corresponding handler object (such as when only the file
495/// descriptor number is required in a closure which may be dropped instead of being executed).
496pub struct Fd(pub RawFd);
497
498impl Drop for Fd {
499 fn drop(&mut self) {
500 if self.0 != -1 {
501 unsafe {
502 libc::close(self.0);
503 }
504 }
505 }
506}
507
508impl AsRawFd for Fd {
509 fn as_raw_fd(&self) -> RawFd {
510 self.0
511 }
512}
513
514impl IntoRawFd for Fd {
515 fn into_raw_fd(mut self) -> RawFd {
516 let fd = self.0;
517 self.0 = -1;
518 fd
519 }
520}
521
522impl FromRawFd for Fd {
523 unsafe fn from_raw_fd(fd: RawFd) -> Self {
524 Self(fd)
525 }
526}
efd1536e
WB
527
528// wrap nix::unistd::pipe2 + O_CLOEXEC into something returning guarded file descriptors
529pub fn pipe() -> Result<(Fd, Fd), Error> {
530 let (pin, pout) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?;
531 Ok((Fd(pin), Fd(pout)))
532}
2edc341b
DM
533
534/// An easy way to convert types to Any
535///
536/// Mostly useful to downcast trait objects (see RpcEnvironment).
537pub trait AsAny {
dd5495d6 538 fn as_any(&self) -> &dyn Any;
2edc341b
DM
539}
540
541impl<T: Any> AsAny for T {
6100071f
WB
542 fn as_any(&self) -> &dyn Any {
543 self
544 }
2edc341b 545}