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