]>
Commit | Line | Data |
---|---|---|
51b499db DM |
1 | //! Tools and utilities |
2 | //! | |
3 | //! This is a collection of small and useful tools. | |
6100071f | 4 | use std::any::Any; |
61653382 | 5 | use std::borrow::Borrow; |
6100071f | 6 | use std::collections::HashMap; |
62ee2eb4 | 7 | use std::hash::BuildHasher; |
98c259b4 | 8 | use std::fs::File; |
b649887e | 9 | use std::io::{self, BufRead, Read, Seek, SeekFrom}; |
98c259b4 | 10 | use std::os::unix::io::RawFd; |
6100071f | 11 | use std::path::Path; |
365bb90f | 12 | |
f7d4e4b5 | 13 | use anyhow::{bail, format_err, Error}; |
af926291 | 14 | use serde_json::Value; |
c5946faf | 15 | use openssl::hash::{hash, DigestBytes, MessageDigest}; |
968a0ab2 | 16 | use percent_encoding::{utf8_percent_encode, AsciiSet}; |
0fe5d605 | 17 | |
00ec8d16 WB |
18 | pub use proxmox::tools::fd::Fd; |
19 | ||
6100071f | 20 | pub mod acl; |
e6513bd5 | 21 | pub mod apt; |
556eb70e | 22 | pub mod async_io; |
6ed25cbe | 23 | pub mod borrow; |
ec01eead | 24 | pub mod cert; |
ea62611d | 25 | pub mod compression; |
bc5c1a9a | 26 | pub mod config; |
a5bdc987 | 27 | pub mod cpio; |
6100071f | 28 | pub mod daemon; |
10effc98 | 29 | pub mod disks; |
4939255f | 30 | pub mod format; |
fb01fd3a WB |
31 | pub mod fs; |
32 | pub mod fuse_loop; | |
33 | pub mod http; | |
9ff747ef | 34 | pub mod json; |
8074d2b0 | 35 | pub mod logrotate; |
45f9b32e | 36 | pub mod loopdev; |
fb01fd3a WB |
37 | pub mod lru_cache; |
38 | pub mod nom; | |
39 | pub mod runtime; | |
59e94227 | 40 | pub mod serde_filter; |
97168f92 | 41 | pub mod socket; |
fb01fd3a | 42 | pub mod statistics; |
7b22fb25 | 43 | pub mod subscription; |
fb01fd3a WB |
44 | pub mod systemd; |
45 | pub mod ticket; | |
46 | pub mod xattr; | |
fdce52aa | 47 | pub mod zip; |
9372c078 | 48 | pub mod sgutils2; |
639a6782 | 49 | pub mod paperkey; |
f1d99e3f | 50 | |
fb01fd3a WB |
51 | pub mod parallel_handler; |
52 | pub use parallel_handler::ParallelHandler; | |
3c9b3702 | 53 | |
f1d99e3f | 54 | mod wrapped_reader_stream; |
fb01fd3a | 55 | pub use wrapped_reader_stream::{AsyncReaderStream, StdChannelStream, WrappedReaderStream}; |
dcd033a5 | 56 | |
943479f5 | 57 | mod async_channel_writer; |
fb01fd3a | 58 | pub use async_channel_writer::AsyncChannelWriter; |
943479f5 | 59 | |
dcd033a5 | 60 | mod std_channel_writer; |
fb01fd3a | 61 | pub use std_channel_writer::StdChannelWriter; |
8cf6e764 | 62 | |
f1d76ecf DC |
63 | mod tokio_writer_adapter; |
64 | pub use tokio_writer_adapter::TokioWriterAdapter; | |
65 | ||
a650f503 | 66 | mod process_locker; |
fb01fd3a | 67 | pub use process_locker::{ProcessLocker, ProcessLockExclusiveGuard, ProcessLockSharedGuard}; |
a650f503 | 68 | |
3b151414 | 69 | mod file_logger; |
fb01fd3a | 70 | pub use file_logger::{FileLogger, FileLogOptions}; |
3b151414 | 71 | |
490be29e | 72 | mod broadcast_future; |
fb01fd3a | 73 | pub use broadcast_future::{BroadcastData, BroadcastFuture}; |
490be29e | 74 | |
fded74d0 | 75 | /// The `BufferedRead` trait provides a single function |
0a72e267 DM |
76 | /// `buffered_read`. It returns a reference to an internal buffer. The |
77 | /// purpose of this traid is to avoid unnecessary data copies. | |
fded74d0 | 78 | pub trait BufferedRead { |
318564ac DM |
79 | /// This functions tries to fill the internal buffers, then |
80 | /// returns a reference to the available data. It returns an empty | |
81 | /// buffer if `offset` points to the end of the file. | |
0a72e267 DM |
82 | fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>; |
83 | } | |
84 | ||
f5f13ebc | 85 | pub fn json_object_to_query(data: Value) -> Result<String, Error> { |
f5f13ebc DM |
86 | let mut query = url::form_urlencoded::Serializer::new(String::new()); |
87 | ||
88 | let object = data.as_object().ok_or_else(|| { | |
89 | format_err!("json_object_to_query: got wrong data type (expected object).") | |
90 | })?; | |
91 | ||
92 | for (key, value) in object { | |
93 | match value { | |
6100071f WB |
94 | Value::Bool(b) => { |
95 | query.append_pair(key, &b.to_string()); | |
96 | } | |
97 | Value::Number(n) => { | |
98 | query.append_pair(key, &n.to_string()); | |
99 | } | |
100 | Value::String(s) => { | |
101 | query.append_pair(key, &s); | |
102 | } | |
f5f13ebc DM |
103 | Value::Array(arr) => { |
104 | for element in arr { | |
105 | match element { | |
6100071f WB |
106 | Value::Bool(b) => { |
107 | query.append_pair(key, &b.to_string()); | |
108 | } | |
109 | Value::Number(n) => { | |
110 | query.append_pair(key, &n.to_string()); | |
111 | } | |
112 | Value::String(s) => { | |
113 | query.append_pair(key, &s); | |
114 | } | |
115 | _ => bail!( | |
116 | "json_object_to_query: unable to handle complex array data types." | |
117 | ), | |
f5f13ebc DM |
118 | } |
119 | } | |
120 | } | |
121 | _ => bail!("json_object_to_query: unable to handle complex data types."), | |
122 | } | |
123 | } | |
124 | ||
125 | Ok(query.finish()) | |
126 | } | |
127 | ||
0fe5d605 | 128 | pub fn required_string_param<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> { |
6100071f | 129 | match param[name].as_str() { |
0fe5d605 DM |
130 | Some(s) => Ok(s), |
131 | None => bail!("missing parameter '{}'", name), | |
132 | } | |
133 | } | |
0d38dcb4 | 134 | |
e17d5d86 DM |
135 | pub fn required_string_property<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> { |
136 | match param[name].as_str() { | |
137 | Some(s) => Ok(s), | |
138 | None => bail!("missing property '{}'", name), | |
139 | } | |
140 | } | |
141 | ||
a4ba60be | 142 | pub fn required_integer_param(param: &Value, name: &str) -> Result<i64, Error> { |
6100071f | 143 | match param[name].as_i64() { |
0d38dcb4 DM |
144 | Some(s) => Ok(s), |
145 | None => bail!("missing parameter '{}'", name), | |
f8dfbb45 DM |
146 | } |
147 | } | |
148 | ||
a4ba60be | 149 | pub fn required_integer_property(param: &Value, name: &str) -> Result<i64, Error> { |
e17d5d86 DM |
150 | match param[name].as_i64() { |
151 | Some(s) => Ok(s), | |
152 | None => bail!("missing property '{}'", name), | |
153 | } | |
154 | } | |
155 | ||
35304303 | 156 | pub fn required_array_param<'a>(param: &'a Value, name: &str) -> Result<&'a [Value], Error> { |
6100071f | 157 | match param[name].as_array() { |
35304303 | 158 | Some(s) => Ok(&s), |
f8dfbb45 | 159 | None => bail!("missing parameter '{}'", name), |
0d38dcb4 DM |
160 | } |
161 | } | |
383e8577 | 162 | |
35304303 | 163 | pub fn required_array_property<'a>(param: &'a Value, name: &str) -> Result<&'a [Value], Error> { |
e17d5d86 | 164 | match param[name].as_array() { |
35304303 | 165 | Some(s) => Ok(&s), |
e17d5d86 DM |
166 | None => bail!("missing property '{}'", name), |
167 | } | |
168 | } | |
169 | ||
a4ba60be WB |
170 | pub fn complete_file_name<S>(arg: &str, _param: &HashMap<String, String, S>) -> Vec<String> |
171 | where | |
172 | S: BuildHasher, | |
173 | { | |
383e8577 DM |
174 | let mut result = vec![]; |
175 | ||
6100071f | 176 | use nix::fcntl::AtFlags; |
383e8577 DM |
177 | use nix::fcntl::OFlag; |
178 | use nix::sys::stat::Mode; | |
383e8577 | 179 | |
62ee2eb4 | 180 | let mut dirname = std::path::PathBuf::from(if arg.is_empty() { "./" } else { arg }); |
383e8577 DM |
181 | |
182 | let is_dir = match nix::sys::stat::fstatat(libc::AT_FDCWD, &dirname, AtFlags::empty()) { | |
183 | Ok(stat) => (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR, | |
184 | Err(_) => false, | |
185 | }; | |
186 | ||
187 | if !is_dir { | |
188 | if let Some(parent) = dirname.parent() { | |
189 | dirname = parent.to_owned(); | |
190 | } | |
191 | } | |
192 | ||
6100071f WB |
193 | let mut dir = |
194 | match nix::dir::Dir::openat(libc::AT_FDCWD, &dirname, OFlag::O_DIRECTORY, Mode::empty()) { | |
195 | Ok(d) => d, | |
196 | Err(_) => return result, | |
197 | }; | |
383e8577 DM |
198 | |
199 | for item in dir.iter() { | |
200 | if let Ok(entry) = item { | |
201 | if let Ok(name) = entry.file_name().to_str() { | |
6100071f WB |
202 | if name == "." || name == ".." { |
203 | continue; | |
204 | } | |
383e8577 DM |
205 | let mut newpath = dirname.clone(); |
206 | newpath.push(name); | |
207 | ||
6100071f WB |
208 | if let Ok(stat) = |
209 | nix::sys::stat::fstatat(libc::AT_FDCWD, &newpath, AtFlags::empty()) | |
210 | { | |
383e8577 DM |
211 | if (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR { |
212 | newpath.push(""); | |
213 | if let Some(newpath) = newpath.to_str() { | |
214 | result.push(newpath.to_owned()); | |
215 | } | |
216 | continue; | |
6100071f | 217 | } |
383e8577 DM |
218 | } |
219 | if let Some(newpath) = newpath.to_str() { | |
220 | result.push(newpath.to_owned()); | |
221 | } | |
6100071f | 222 | } |
383e8577 DM |
223 | } |
224 | } | |
225 | ||
226 | result | |
227 | } | |
443f3743 DM |
228 | |
229 | /// Scan directory for matching file names. | |
230 | /// | |
231 | /// Scan through all directory entries and call `callback()` function | |
232 | /// if the entry name matches the regular expression. This function | |
233 | /// used unix `openat()`, so you can pass absolute or relative file | |
234 | /// names. This function simply skips non-UTF8 encoded names. | |
235 | pub fn scandir<P, F>( | |
236 | dirfd: RawFd, | |
121f18ef | 237 | path: &P, |
443f3743 | 238 | regex: ®ex::Regex, |
6100071f | 239 | mut callback: F, |
443f3743 | 240 | ) -> Result<(), Error> |
6100071f WB |
241 | where |
242 | F: FnMut(RawFd, &str, nix::dir::Type) -> Result<(), Error>, | |
243 | P: ?Sized + nix::NixPath, | |
443f3743 | 244 | { |
121f18ef | 245 | for entry in self::fs::scan_subdir(dirfd, path, regex)? { |
443f3743 DM |
246 | let entry = entry?; |
247 | let file_type = match entry.file_type() { | |
248 | Some(file_type) => file_type, | |
249 | None => bail!("unable to detect file type"), | |
250 | }; | |
443f3743 | 251 | |
6100071f WB |
252 | callback( |
253 | entry.parent_fd(), | |
254 | unsafe { entry.file_name_utf8_unchecked() }, | |
255 | file_type, | |
256 | )?; | |
443f3743 DM |
257 | } |
258 | Ok(()) | |
259 | } | |
7e13b2d6 | 260 | |
c5946faf WB |
261 | /// Shortcut for md5 sums. |
262 | pub fn md5sum(data: &[u8]) -> Result<DigestBytes, Error> { | |
263 | hash(MessageDigest::md5(), data).map_err(Error::from) | |
264 | } | |
265 | ||
7e13b2d6 | 266 | pub fn get_hardware_address() -> Result<String, Error> { |
1631c54f | 267 | static FILENAME: &str = "/etc/ssh/ssh_host_rsa_key.pub"; |
7e13b2d6 | 268 | |
72c0e102 TL |
269 | let contents = proxmox::tools::fs::file_get_contents(FILENAME) |
270 | .map_err(|e| format_err!("Error getting host key - {}", e))?; | |
271 | let digest = md5sum(&contents) | |
272 | .map_err(|e| format_err!("Error digesting host key - {}", e))?; | |
7e13b2d6 | 273 | |
52fe9e8e | 274 | Ok(proxmox::tools::bin_to_hex(&digest).to_uppercase()) |
7e13b2d6 | 275 | } |
22968600 | 276 | |
af2fddea DM |
277 | pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> { |
278 | if digest1 != digest2 { | |
6100071f | 279 | bail!("detected modified configuration - file changed by other user? Try again."); |
af2fddea DM |
280 | } |
281 | Ok(()) | |
282 | } | |
b9903d63 | 283 | |
09f12d1c | 284 | /// Extract a specific cookie from cookie header. |
b9903d63 | 285 | /// We assume cookie_name is already url encoded. |
09f12d1c | 286 | pub fn extract_cookie(cookie: &str, cookie_name: &str) -> Option<String> { |
b9903d63 | 287 | for pair in cookie.split(';') { |
b9903d63 DM |
288 | let (name, value) = match pair.find('=') { |
289 | Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()), | |
290 | None => return None, // Cookie format error | |
291 | }; | |
292 | ||
293 | if name == cookie_name { | |
8a1028e0 | 294 | use percent_encoding::percent_decode; |
b9903d63 DM |
295 | if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() { |
296 | return Some(value.into()); | |
297 | } else { | |
298 | return None; // Cookie format error | |
299 | } | |
300 | } | |
301 | } | |
302 | ||
303 | None | |
304 | } | |
af53186e | 305 | |
968a0ab2 DC |
306 | /// percent encode a url component |
307 | pub fn percent_encode_component(comp: &str) -> String { | |
308 | utf8_percent_encode(comp, percent_encoding::NON_ALPHANUMERIC).to_string() | |
309 | } | |
310 | ||
61653382 | 311 | pub fn join<S: Borrow<str>>(data: &[S], sep: char) -> String { |
af53186e DM |
312 | let mut list = String::new(); |
313 | ||
314 | for item in data { | |
62ee2eb4 | 315 | if !list.is_empty() { |
6100071f WB |
316 | list.push(sep); |
317 | } | |
61653382 | 318 | list.push_str(item.borrow()); |
af53186e DM |
319 | } |
320 | ||
321 | list | |
322 | } | |
ff7049d4 | 323 | |
002a191a DM |
324 | /// Detect modified configuration files |
325 | /// | |
add5861e | 326 | /// This function fails with a reasonable error message if checksums do not match. |
002a191a DM |
327 | pub fn detect_modified_configuration_file(digest1: &[u8;32], digest2: &[u8;32]) -> Result<(), Error> { |
328 | if digest1 != digest2 { | |
a4ba60be | 329 | bail!("detected modified configuration - file changed by other user? Try again."); |
002a191a DM |
330 | } |
331 | Ok(()) | |
332 | } | |
333 | ||
3578d99f DM |
334 | /// normalize uri path |
335 | /// | |
336 | /// Do not allow ".", "..", or hidden files ".XXXX" | |
337 | /// Also remove empty path components | |
338 | pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> { | |
3578d99f DM |
339 | let items = path.split('/'); |
340 | ||
341 | let mut path = String::new(); | |
342 | let mut components = vec![]; | |
343 | ||
344 | for name in items { | |
6100071f WB |
345 | if name.is_empty() { |
346 | continue; | |
347 | } | |
62ee2eb4 | 348 | if name.starts_with('.') { |
3578d99f DM |
349 | bail!("Path contains illegal components."); |
350 | } | |
351 | path.push('/'); | |
352 | path.push_str(name); | |
353 | components.push(name); | |
354 | } | |
355 | ||
356 | Ok((path, components)) | |
357 | } | |
358 | ||
97fab7aa | 359 | /// Helper to check result from std::process::Command output |
143b6545 DM |
360 | /// |
361 | /// The exit_code_check() function should return true if the exit code | |
362 | /// is considered successful. | |
363 | pub fn command_output( | |
364 | output: std::process::Output, | |
144006fa | 365 | exit_code_check: Option<fn(i32) -> bool>, |
e64b9f92 | 366 | ) -> Result<Vec<u8>, Error> { |
97fab7aa DM |
367 | |
368 | if !output.status.success() { | |
369 | match output.status.code() { | |
370 | Some(code) => { | |
143b6545 DM |
371 | let is_ok = match exit_code_check { |
372 | Some(check_fn) => check_fn(code), | |
373 | None => code == 0, | |
374 | }; | |
375 | if !is_ok { | |
97fab7aa DM |
376 | let msg = String::from_utf8(output.stderr) |
377 | .map(|m| if m.is_empty() { String::from("no error message") } else { m }) | |
378 | .unwrap_or_else(|_| String::from("non utf8 error message (suppressed)")); | |
379 | ||
380 | bail!("status code: {} - {}", code, msg); | |
381 | } | |
382 | } | |
383 | None => bail!("terminated by signal"), | |
384 | } | |
385 | } | |
386 | ||
e64b9f92 DM |
387 | Ok(output.stdout) |
388 | } | |
97fab7aa | 389 | |
e64b9f92 DM |
390 | /// Helper to check result from std::process::Command output, returns String. |
391 | /// | |
392 | /// The exit_code_check() function should return true if the exit code | |
393 | /// is considered successful. | |
394 | pub fn command_output_as_string( | |
395 | output: std::process::Output, | |
396 | exit_code_check: Option<fn(i32) -> bool>, | |
397 | ) -> Result<String, Error> { | |
398 | let output = command_output(output, exit_code_check)?; | |
399 | let output = String::from_utf8(output)?; | |
97fab7aa DM |
400 | Ok(output) |
401 | } | |
402 | ||
144006fa DM |
403 | pub fn run_command( |
404 | mut command: std::process::Command, | |
405 | exit_code_check: Option<fn(i32) -> bool>, | |
406 | ) -> Result<String, Error> { | |
407 | ||
408 | let output = command.output() | |
409 | .map_err(|err| format_err!("failed to execute {:?} - {}", command, err))?; | |
410 | ||
f254a270 | 411 | let output = command_output_as_string(output, exit_code_check) |
144006fa DM |
412 | .map_err(|err| format_err!("command {:?} failed - {}", command, err))?; |
413 | ||
414 | Ok(output) | |
415 | } | |
97fab7aa | 416 | |
ff7049d4 | 417 | pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> { |
6100071f | 418 | use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD}; |
ff7049d4 WB |
419 | let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?) |
420 | .ok_or_else(|| format_err!("unhandled file flags"))?; // nix crate is stupid this way... | |
421 | flags.set(FdFlag::FD_CLOEXEC, on); | |
422 | fcntl(fd, F_SETFD(flags))?; | |
423 | Ok(()) | |
424 | } | |
9136f857 | 425 | |
9136f857 DM |
426 | static mut SHUTDOWN_REQUESTED: bool = false; |
427 | ||
428 | pub fn request_shutdown() { | |
6100071f WB |
429 | unsafe { |
430 | SHUTDOWN_REQUESTED = true; | |
431 | } | |
7a630df7 | 432 | crate::server::server_shutdown(); |
9136f857 DM |
433 | } |
434 | ||
435 | #[inline(always)] | |
436 | pub fn shutdown_requested() -> bool { | |
437 | unsafe { SHUTDOWN_REQUESTED } | |
438 | } | |
92da93b2 DM |
439 | |
440 | pub fn fail_on_shutdown() -> Result<(), Error> { | |
441 | if shutdown_requested() { | |
442 | bail!("Server shutdown requested - aborting task"); | |
443 | } | |
444 | Ok(()) | |
445 | } | |
d96bb7f1 | 446 | |
c4044009 WB |
447 | /// safe wrapper for `nix::unistd::pipe2` defaulting to `O_CLOEXEC` and guarding the file |
448 | /// descriptors. | |
efd1536e WB |
449 | pub fn pipe() -> Result<(Fd, Fd), Error> { |
450 | let (pin, pout) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?; | |
451 | Ok((Fd(pin), Fd(pout))) | |
452 | } | |
2edc341b | 453 | |
c4044009 WB |
454 | /// safe wrapper for `nix::sys::socket::socketpair` defaulting to `O_CLOEXEC` and guarding the file |
455 | /// descriptors. | |
456 | pub fn socketpair() -> Result<(Fd, Fd), Error> { | |
457 | use nix::sys::socket; | |
458 | let (pa, pb) = socket::socketpair( | |
459 | socket::AddressFamily::Unix, | |
460 | socket::SockType::Stream, | |
461 | None, | |
462 | socket::SockFlag::SOCK_CLOEXEC, | |
463 | )?; | |
464 | Ok((Fd(pa), Fd(pb))) | |
465 | } | |
466 | ||
467 | ||
2edc341b DM |
468 | /// An easy way to convert types to Any |
469 | /// | |
470 | /// Mostly useful to downcast trait objects (see RpcEnvironment). | |
471 | pub trait AsAny { | |
dd5495d6 | 472 | fn as_any(&self) -> &dyn Any; |
2edc341b DM |
473 | } |
474 | ||
475 | impl<T: Any> AsAny for T { | |
6100071f WB |
476 | fn as_any(&self) -> &dyn Any { |
477 | self | |
478 | } | |
2edc341b | 479 | } |
8a1028e0 WB |
480 | |
481 | /// This used to be: `SIMPLE_ENCODE_SET` plus space, `"`, `#`, `<`, `>`, backtick, `?`, `{`, `}` | |
482 | pub const DEFAULT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS // 0..1f and 7e | |
483 | // The SIMPLE_ENCODE_SET adds space and anything >= 0x7e (7e itself is already included above) | |
484 | .add(0x20) | |
485 | .add(0x7f) | |
486 | // the DEFAULT_ENCODE_SET added: | |
487 | .add(b' ') | |
488 | .add(b'"') | |
489 | .add(b'#') | |
490 | .add(b'<') | |
491 | .add(b'>') | |
492 | .add(b'`') | |
493 | .add(b'?') | |
494 | .add(b'{') | |
495 | .add(b'}'); | |
386990ba WB |
496 | |
497 | /// Get an iterator over lines of a file, skipping empty lines and comments (lines starting with a | |
498 | /// `#`). | |
499 | pub fn file_get_non_comment_lines<P: AsRef<Path>>( | |
500 | path: P, | |
501 | ) -> Result<impl Iterator<Item = io::Result<String>>, Error> { | |
502 | let path = path.as_ref(); | |
503 | ||
504 | Ok(io::BufReader::new( | |
505 | File::open(path).map_err(|err| format_err!("error opening {:?}: {}", path, err))?, | |
506 | ) | |
507 | .lines() | |
508 | .filter_map(|line| match line { | |
509 | Ok(line) => { | |
510 | let line = line.trim(); | |
511 | if line.is_empty() || line.starts_with('#') { | |
512 | None | |
513 | } else { | |
514 | Some(Ok(line.to_string())) | |
515 | } | |
516 | } | |
517 | Err(err) => Some(Err(err)), | |
518 | })) | |
519 | } | |
e693818a | 520 | |
ac7513e3 DM |
521 | pub fn setup_safe_path_env() { |
522 | std::env::set_var("PATH", "/sbin:/bin:/usr/sbin:/usr/bin"); | |
523 | // Make %ENV safer - as suggested by https://perldoc.perl.org/perlsec.html | |
524 | for name in &["IFS", "CDPATH", "ENV", "BASH_ENV"] { | |
525 | std::env::remove_var(name); | |
526 | } | |
527 | } | |
cdf1da28 WB |
528 | |
529 | pub fn strip_ascii_whitespace(line: &[u8]) -> &[u8] { | |
530 | let line = match line.iter().position(|&b| !b.is_ascii_whitespace()) { | |
531 | Some(n) => &line[n..], | |
532 | None => return &[], | |
533 | }; | |
534 | match line.iter().rev().position(|&b| !b.is_ascii_whitespace()) { | |
535 | Some(n) => &line[..(line.len() - n)], | |
536 | None => &[], | |
537 | } | |
538 | } | |
1bc1d81a DM |
539 | |
540 | /// Seeks to start of file and computes the SHA256 hash | |
541 | pub fn compute_file_csum(file: &mut File) -> Result<([u8; 32], u64), Error> { | |
542 | ||
543 | file.seek(SeekFrom::Start(0))?; | |
544 | ||
545 | let mut hasher = openssl::sha::Sha256::new(); | |
546 | let mut buffer = proxmox::tools::vec::undefined(256*1024); | |
547 | let mut size: u64 = 0; | |
548 | ||
549 | loop { | |
550 | let count = match file.read(&mut buffer) { | |
a4ba60be | 551 | Ok(0) => break, |
1bc1d81a DM |
552 | Ok(count) => count, |
553 | Err(ref err) if err.kind() == std::io::ErrorKind::Interrupted => { | |
554 | continue; | |
555 | } | |
556 | Err(err) => return Err(err.into()), | |
557 | }; | |
1bc1d81a DM |
558 | size += count as u64; |
559 | hasher.update(&buffer[..count]); | |
560 | } | |
561 | ||
562 | let csum = hasher.finish(); | |
563 | ||
564 | Ok((csum, size)) | |
565 | } | |
014dc5f9 WB |
566 | |
567 | /// Create the base run-directory. | |
568 | /// | |
569 | /// This exists to fixate the permissions for the run *base* directory while allowing intermediate | |
570 | /// directories after it to have different permissions. | |
571 | pub fn create_run_dir() -> Result<(), Error> { | |
572 | let _: bool = proxmox::tools::fs::create_path(PROXMOX_BACKUP_RUN_DIR_M!(), None, None)?; | |
573 | Ok(()) | |
574 | } | |
0b6d9442 WB |
575 | |
576 | /// Modeled after the nightly `std::ops::ControlFlow`. | |
577 | #[derive(Clone, Copy, Debug, PartialEq)] | |
578 | pub enum ControlFlow<B, C = ()> { | |
579 | Continue(C), | |
580 | Break(B), | |
581 | } | |
582 | ||
583 | impl<B> ControlFlow<B> { | |
584 | pub const CONTINUE: ControlFlow<B, ()> = ControlFlow::Continue(()); | |
585 | } |