]>
Commit | Line | Data |
---|---|---|
51b499db DM |
1 | //! Tools and utilities |
2 | //! | |
3 | //! This is a collection of small and useful tools. | |
f12f8ff1 DM |
4 | use failure::*; |
5 | use nix::unistd; | |
6 | use nix::sys::stat; | |
7 | ||
74a69302 DM |
8 | use lazy_static::lazy_static; |
9 | ||
365bb90f | 10 | use std::fs::{File, OpenOptions}; |
f12f8ff1 DM |
11 | use std::io::Write; |
12 | use std::path::Path; | |
43eeef28 DM |
13 | use std::io::Read; |
14 | use std::io::ErrorKind; | |
1628a4c7 | 15 | use std::time::Duration; |
f12f8ff1 | 16 | |
443f3743 | 17 | use std::os::unix::io::RawFd; |
eae8aa3a | 18 | use std::os::unix::io::AsRawFd; |
365bb90f | 19 | |
0fe5d605 DM |
20 | use serde_json::Value; |
21 | ||
8cf6e764 | 22 | pub mod timer; |
7f0d67cf | 23 | pub mod wrapped_reader_stream; |
8f973f81 DM |
24 | #[macro_use] |
25 | pub mod common_regex; | |
8d04280b | 26 | pub mod ticket; |
6ed25cbe | 27 | pub mod borrow; |
b4d5787d | 28 | pub mod fs; |
c9b296f1 | 29 | pub mod tty; |
8cf6e764 | 30 | |
3b151414 DM |
31 | #[macro_use] |
32 | mod file_logger; | |
33 | pub use file_logger::*; | |
34 | ||
e80503d2 DM |
35 | /// Macro to write error-handling blocks (like perl eval {}) |
36 | /// | |
37 | /// #### Example: | |
38 | /// ``` | |
fe651dd6 DM |
39 | /// # #[macro_use] extern crate proxmox_backup; |
40 | /// # use failure::*; | |
41 | /// # let some_condition = false; | |
e80503d2 DM |
42 | /// let result = try_block!({ |
43 | /// if (some_condition) { | |
44 | /// bail!("some error"); | |
45 | /// } | |
46 | /// Ok(()) | |
47 | /// }) | |
48 | /// .map_err(|e| format_err!("my try block returned an error - {}", e)); | |
49 | /// ``` | |
50 | ||
f0dbba8c DM |
51 | #[macro_export] |
52 | macro_rules! try_block { | |
53 | { $($token:tt)* } => {{ (|| -> Result<_,_> { $($token)* })() }} | |
54 | } | |
55 | ||
5d14eb6a | 56 | |
fded74d0 | 57 | /// The `BufferedRead` trait provides a single function |
0a72e267 DM |
58 | /// `buffered_read`. It returns a reference to an internal buffer. The |
59 | /// purpose of this traid is to avoid unnecessary data copies. | |
fded74d0 | 60 | pub trait BufferedRead { |
318564ac DM |
61 | /// This functions tries to fill the internal buffers, then |
62 | /// returns a reference to the available data. It returns an empty | |
63 | /// buffer if `offset` points to the end of the file. | |
0a72e267 DM |
64 | fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>; |
65 | } | |
66 | ||
51b499db DM |
67 | /// Directly map a type into a binary buffer. This is mostly useful |
68 | /// for reading structured data from a byte stream (file). You need to | |
69 | /// make sure that the buffer location does not change, so please | |
70 | /// avoid vec resize while you use such map. | |
71 | /// | |
72 | /// This function panics if the buffer is not large enough. | |
50ea4396 | 73 | pub fn map_struct<T>(buffer: &[u8]) -> Result<&T, Error> { |
dc3de618 DM |
74 | if buffer.len() < ::std::mem::size_of::<T>() { |
75 | bail!("unable to map struct - buffer too small"); | |
76 | } | |
95bd5dfe | 77 | Ok(unsafe { & * (buffer.as_ptr() as *const T) }) |
dc3de618 DM |
78 | } |
79 | ||
51b499db DM |
80 | /// Directly map a type into a mutable binary buffer. This is mostly |
81 | /// useful for writing structured data into a byte stream (file). You | |
82 | /// need to make sure that the buffer location does not change, so | |
83 | /// please avoid vec resize while you use such map. | |
84 | /// | |
85 | /// This function panics if the buffer is not large enough. | |
50ea4396 | 86 | pub fn map_struct_mut<T>(buffer: &mut [u8]) -> Result<&mut T, Error> { |
dc3de618 DM |
87 | if buffer.len() < ::std::mem::size_of::<T>() { |
88 | bail!("unable to map struct - buffer too small"); | |
89 | } | |
95bd5dfe | 90 | Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) }) |
dc3de618 DM |
91 | } |
92 | ||
6235a418 | 93 | pub fn file_read_firstline<P: AsRef<Path>>(path: P) -> Result<String, Error> { |
447787ab DM |
94 | |
95 | let path = path.as_ref(); | |
96 | ||
6235a418 DM |
97 | try_block!({ |
98 | let file = std::fs::File::open(path)?; | |
447787ab | 99 | |
6235a418 | 100 | use std::io::{BufRead, BufReader}; |
447787ab | 101 | |
6235a418 | 102 | let mut reader = BufReader::new(file); |
447787ab | 103 | |
6235a418 | 104 | let mut line = String::new(); |
447787ab | 105 | |
6235a418 | 106 | let _ = reader.read_line(&mut line)?; |
447787ab | 107 | |
6235a418 DM |
108 | Ok(line) |
109 | }).map_err(|err: Error| format_err!("unable to read {:?} - {}", path, err)) | |
447787ab DM |
110 | } |
111 | ||
12400210 DM |
112 | pub fn file_get_contents<P: AsRef<Path>>(path: P) -> Result<Vec<u8>, Error> { |
113 | ||
114 | let path = path.as_ref(); | |
115 | ||
116 | try_block!({ | |
117 | std::fs::read(path) | |
118 | }).map_err(|err| format_err!("unable to read {:?} - {}", path, err)) | |
53157ca6 DM |
119 | } |
120 | ||
51b499db DM |
121 | /// Atomically write a file. We first create a temporary file, which |
122 | /// is then renamed. | |
f12f8ff1 DM |
123 | pub fn file_set_contents<P: AsRef<Path>>( |
124 | path: P, | |
125 | data: &[u8], | |
126 | perm: Option<stat::Mode>, | |
127 | ) -> Result<(), Error> { | |
128 | ||
129 | let path = path.as_ref(); | |
130 | ||
d64d80d2 DM |
131 | // Note: we use mkstemp heŕe, because this worka with different |
132 | // processes, threads, and even tokio tasks. | |
f12f8ff1 DM |
133 | let mut template = path.to_owned(); |
134 | template.set_extension("tmp_XXXXXX"); | |
135 | let (fd, tmp_path) = match unistd::mkstemp(&template) { | |
136 | Ok((fd, path)) => (fd, path), | |
137 | Err(err) => bail!("mkstemp {:?} failed: {}", template, err), | |
138 | }; | |
139 | ||
140 | let tmp_path = tmp_path.as_path(); | |
141 | ||
1a7bc3dd | 142 | let mode : stat::Mode = perm.unwrap_or(stat::Mode::from( |
f12f8ff1 DM |
143 | stat::Mode::S_IRUSR | stat::Mode::S_IWUSR | |
144 | stat::Mode::S_IRGRP | stat::Mode::S_IROTH | |
1a7bc3dd | 145 | )); |
f12f8ff1 DM |
146 | |
147 | if let Err(err) = stat::fchmod(fd, mode) { | |
148 | let _ = unistd::unlink(tmp_path); | |
149 | bail!("fchmod {:?} failed: {}", tmp_path, err); | |
150 | } | |
151 | ||
152 | use std::os::unix::io::FromRawFd; | |
153 | let mut file = unsafe { File::from_raw_fd(fd) }; | |
154 | ||
155 | if let Err(err) = file.write_all(data) { | |
156 | let _ = unistd::unlink(tmp_path); | |
157 | bail!("write failed: {}", err); | |
158 | } | |
159 | ||
160 | if let Err(err) = std::fs::rename(tmp_path, path) { | |
161 | let _ = unistd::unlink(tmp_path); | |
162 | bail!("Atomic rename failed for file {:?} - {}", path, err); | |
163 | } | |
164 | ||
165 | Ok(()) | |
166 | } | |
43eeef28 | 167 | |
51b499db DM |
168 | /// Create a file lock using fntl. This function allows you to specify |
169 | /// a timeout if you want to avoid infinite blocking. | |
1628a4c7 WB |
170 | pub fn lock_file<F: AsRawFd>( |
171 | file: &mut F, | |
172 | exclusive: bool, | |
173 | timeout: Option<Duration>, | |
174 | ) -> Result<(), Error> | |
175 | { | |
176 | let lockarg = | |
177 | if exclusive { | |
178 | nix::fcntl::FlockArg::LockExclusive | |
179 | } else { | |
180 | nix::fcntl::FlockArg::LockShared | |
181 | }; | |
182 | ||
183 | let timeout = match timeout { | |
184 | None => { | |
185 | nix::fcntl::flock(file.as_raw_fd(), lockarg)?; | |
186 | return Ok(()); | |
187 | } | |
188 | Some(t) => t, | |
189 | }; | |
190 | ||
191 | // unblock the timeout signal temporarily | |
192 | let _sigblock_guard = timer::unblock_timeout_signal(); | |
193 | ||
194 | // setup a timeout timer | |
195 | let mut timer = timer::Timer::create( | |
196 | timer::Clock::Realtime, | |
197 | timer::TimerEvent::ThisThreadSignal(timer::SIGTIMEOUT))?; | |
198 | ||
199 | timer.arm(timer::TimerSpec::new() | |
200 | .value(Some(timeout)) | |
201 | .interval(Some(Duration::from_millis(10))))?; | |
202 | ||
203 | nix::fcntl::flock(file.as_raw_fd(), lockarg)?; | |
204 | Ok(()) | |
205 | } | |
365bb90f | 206 | |
51b499db DM |
207 | /// Open or create a lock file (append mode). Then try to |
208 | /// aquire a lock using `lock_file()`. | |
1628a4c7 WB |
209 | pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration) |
210 | -> Result<File, Error> | |
211 | { | |
212 | let path = path.as_ref(); | |
213 | let mut file = | |
214 | match OpenOptions::new() | |
215 | .create(true) | |
216 | .append(true) | |
217 | .open(path) | |
218 | { | |
365bb90f DM |
219 | Ok(file) => file, |
220 | Err(err) => bail!("Unable to open lock {:?} - {}", | |
221 | path, err), | |
222 | }; | |
28b96b56 DM |
223 | match lock_file(&mut file, true, Some(timeout)) { |
224 | Ok(_) => Ok(file), | |
225 | Err(err) => bail!("Unable to aquire lock {:?} - {}", | |
226 | path, err), | |
227 | } | |
365bb90f DM |
228 | } |
229 | ||
51b499db DM |
230 | /// Split a file into equal sized chunks. The last chunk may be |
231 | /// smaller. Note: We cannot implement an `Iterator`, because iterators | |
232 | /// cannot return a borrowed buffer ref (we want zero-copy) | |
43eeef28 DM |
233 | pub fn file_chunker<C, R>( |
234 | mut file: R, | |
235 | chunk_size: usize, | |
606ce64b | 236 | mut chunk_cb: C |
43eeef28 | 237 | ) -> Result<(), Error> |
606ce64b | 238 | where C: FnMut(usize, &[u8]) -> Result<bool, Error>, |
43eeef28 DM |
239 | R: Read, |
240 | { | |
241 | ||
242 | const READ_BUFFER_SIZE: usize = 4*1024*1024; // 4M | |
243 | ||
244 | if chunk_size > READ_BUFFER_SIZE { bail!("chunk size too large!"); } | |
245 | ||
246 | let mut buf = vec![0u8; READ_BUFFER_SIZE]; | |
247 | ||
248 | let mut pos = 0; | |
249 | let mut file_pos = 0; | |
250 | loop { | |
251 | let mut eof = false; | |
252 | let mut tmp = &mut buf[..]; | |
253 | // try to read large portions, at least chunk_size | |
254 | while pos < chunk_size { | |
255 | match file.read(tmp) { | |
256 | Ok(0) => { eof = true; break; }, | |
257 | Ok(n) => { | |
258 | pos += n; | |
259 | if pos > chunk_size { break; } | |
260 | tmp = &mut tmp[n..]; | |
261 | } | |
262 | Err(ref e) if e.kind() == ErrorKind::Interrupted => { /* try again */ } | |
5f0c2d56 | 263 | Err(e) => bail!("read chunk failed - {}", e.to_string()), |
43eeef28 DM |
264 | } |
265 | } | |
43eeef28 DM |
266 | let mut start = 0; |
267 | while start + chunk_size <= pos { | |
268 | if !(chunk_cb)(file_pos, &buf[start..start+chunk_size])? { break; } | |
269 | file_pos += chunk_size; | |
270 | start += chunk_size; | |
271 | } | |
272 | if eof { | |
273 | if start < pos { | |
274 | (chunk_cb)(file_pos, &buf[start..pos])?; | |
275 | //file_pos += pos - start; | |
276 | } | |
277 | break; | |
278 | } else { | |
279 | let rest = pos - start; | |
280 | if rest > 0 { | |
281 | let ptr = buf.as_mut_ptr(); | |
282 | unsafe { std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest); } | |
283 | pos = rest; | |
284 | } else { | |
285 | pos = 0; | |
286 | } | |
287 | } | |
288 | } | |
289 | ||
290 | Ok(()) | |
43eeef28 | 291 | } |
0fe5d605 | 292 | |
5d14eb6a DM |
293 | // Returns the Unix uid/gid for the sepcified system user. |
294 | pub fn getpwnam_ugid(username: &str) -> Result<(libc::uid_t,libc::gid_t), Error> { | |
295 | let info = unsafe { libc::getpwnam(std::ffi::CString::new(username).unwrap().as_ptr()) }; | |
296 | if info == std::ptr::null_mut() { | |
297 | bail!("getwpnam '{}' failed", username); | |
298 | } | |
299 | ||
300 | let info = unsafe { *info }; | |
301 | ||
302 | Ok((info.pw_uid, info.pw_gid)) | |
303 | } | |
304 | ||
305 | // Returns the hosts node name (UTS node name) | |
74a69302 DM |
306 | pub fn nodename() -> &'static str { |
307 | ||
308 | lazy_static!{ | |
309 | static ref NODENAME: String = { | |
310 | ||
0d38dcb4 DM |
311 | nix::sys::utsname::uname() |
312 | .nodename() | |
313 | .split('.') | |
314 | .next() | |
315 | .unwrap() | |
316 | .to_owned() | |
74a69302 DM |
317 | }; |
318 | } | |
319 | ||
320 | &NODENAME | |
321 | } | |
322 | ||
0fe5d605 DM |
323 | pub fn required_string_param<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> { |
324 | match param[name].as_str() { | |
325 | Some(s) => Ok(s), | |
326 | None => bail!("missing parameter '{}'", name), | |
327 | } | |
328 | } | |
0d38dcb4 DM |
329 | |
330 | pub fn required_integer_param<'a>(param: &'a Value, name: &str) -> Result<i64, Error> { | |
331 | match param[name].as_i64() { | |
332 | Some(s) => Ok(s), | |
333 | None => bail!("missing parameter '{}'", name), | |
f8dfbb45 DM |
334 | } |
335 | } | |
336 | ||
337 | pub fn required_array_param<'a>(param: &'a Value, name: &str) -> Result<Vec<Value>, Error> { | |
338 | match param[name].as_array() { | |
339 | Some(s) => Ok(s.to_vec()), | |
340 | None => bail!("missing parameter '{}'", name), | |
0d38dcb4 DM |
341 | } |
342 | } | |
383e8577 DM |
343 | |
344 | pub fn complete_file_name(arg: &str) -> Vec<String> { | |
345 | ||
346 | let mut result = vec![]; | |
347 | ||
348 | use nix::fcntl::OFlag; | |
349 | use nix::sys::stat::Mode; | |
350 | use nix::fcntl::AtFlags; | |
351 | ||
352 | let mut dirname = std::path::PathBuf::from(arg); | |
353 | ||
354 | let is_dir = match nix::sys::stat::fstatat(libc::AT_FDCWD, &dirname, AtFlags::empty()) { | |
355 | Ok(stat) => (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR, | |
356 | Err(_) => false, | |
357 | }; | |
358 | ||
359 | if !is_dir { | |
360 | if let Some(parent) = dirname.parent() { | |
361 | dirname = parent.to_owned(); | |
362 | } | |
363 | } | |
364 | ||
365 | let mut dir = match nix::dir::Dir::openat(libc::AT_FDCWD, &dirname, OFlag::O_DIRECTORY, Mode::empty()) { | |
366 | Ok(d) => d, | |
367 | Err(_) => return result, | |
368 | }; | |
369 | ||
370 | for item in dir.iter() { | |
371 | if let Ok(entry) = item { | |
372 | if let Ok(name) = entry.file_name().to_str() { | |
373 | if name == "." || name == ".." { continue; } | |
374 | let mut newpath = dirname.clone(); | |
375 | newpath.push(name); | |
376 | ||
377 | if let Ok(stat) = nix::sys::stat::fstatat(libc::AT_FDCWD, &newpath, AtFlags::empty()) { | |
378 | if (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR { | |
379 | newpath.push(""); | |
380 | if let Some(newpath) = newpath.to_str() { | |
381 | result.push(newpath.to_owned()); | |
382 | } | |
383 | continue; | |
384 | } | |
385 | } | |
386 | if let Some(newpath) = newpath.to_str() { | |
387 | result.push(newpath.to_owned()); | |
388 | } | |
389 | ||
390 | } | |
391 | } | |
392 | } | |
393 | ||
394 | result | |
395 | } | |
443f3743 DM |
396 | |
397 | /// Scan directory for matching file names. | |
398 | /// | |
399 | /// Scan through all directory entries and call `callback()` function | |
400 | /// if the entry name matches the regular expression. This function | |
401 | /// used unix `openat()`, so you can pass absolute or relative file | |
402 | /// names. This function simply skips non-UTF8 encoded names. | |
403 | pub fn scandir<P, F>( | |
404 | dirfd: RawFd, | |
121f18ef | 405 | path: &P, |
443f3743 | 406 | regex: ®ex::Regex, |
cce1676a | 407 | mut callback: F |
443f3743 | 408 | ) -> Result<(), Error> |
cce1676a | 409 | where F: FnMut(RawFd, &str, nix::dir::Type) -> Result<(), Error>, |
121f18ef | 410 | P: ?Sized + nix::NixPath, |
443f3743 | 411 | { |
121f18ef | 412 | for entry in self::fs::scan_subdir(dirfd, path, regex)? { |
443f3743 DM |
413 | let entry = entry?; |
414 | let file_type = match entry.file_type() { | |
415 | Some(file_type) => file_type, | |
416 | None => bail!("unable to detect file type"), | |
417 | }; | |
443f3743 | 418 | |
121f18ef | 419 | callback(entry.parent_fd(), unsafe { entry.file_name_utf8_unchecked() }, file_type)?; |
443f3743 DM |
420 | } |
421 | Ok(()) | |
422 | } | |
7e13b2d6 DM |
423 | |
424 | pub fn get_hardware_address() -> Result<String, Error> { | |
425 | ||
1631c54f | 426 | static FILENAME: &str = "/etc/ssh/ssh_host_rsa_key.pub"; |
7e13b2d6 | 427 | |
1631c54f | 428 | let contents = file_get_contents(FILENAME)?; |
7e13b2d6 DM |
429 | let digest = md5::compute(contents); |
430 | ||
431 | Ok(format!("{:0x}", digest)) | |
432 | } | |
22968600 DM |
433 | |
434 | pub fn digest_to_hex(digest: &[u8]) -> String { | |
435 | ||
436 | const HEX_CHARS: &'static [u8; 16] = b"0123456789abcdef"; | |
437 | ||
438 | let mut buf = Vec::<u8>::with_capacity(digest.len()*2); | |
439 | ||
440 | for i in 0..digest.len() { | |
441 | buf.push(HEX_CHARS[(digest[i] >> 4) as usize]); | |
442 | buf.push(HEX_CHARS[(digest[i] & 0xf) as usize]); | |
443 | } | |
444 | ||
445 | unsafe { String::from_utf8_unchecked(buf) } | |
446 | } | |
447 | ||
af2fddea DM |
448 | pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> { |
449 | if digest1 != digest2 { | |
450 | bail!("detected modified configuration - file changed by other user? Try again."); | |
451 | } | |
452 | Ok(()) | |
453 | } | |
b9903d63 DM |
454 | |
455 | /// Extract authentication cookie from cookie header. | |
456 | /// We assume cookie_name is already url encoded. | |
457 | pub fn extract_auth_cookie(cookie: &str, cookie_name: &str) -> Option<String> { | |
458 | ||
459 | for pair in cookie.split(';') { | |
460 | ||
461 | let (name, value) = match pair.find('=') { | |
462 | Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()), | |
463 | None => return None, // Cookie format error | |
464 | }; | |
465 | ||
466 | if name == cookie_name { | |
467 | use url::percent_encoding::percent_decode; | |
468 | if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() { | |
469 | return Some(value.into()); | |
470 | } else { | |
471 | return None; // Cookie format error | |
472 | } | |
473 | } | |
474 | } | |
475 | ||
476 | None | |
477 | } | |
af53186e DM |
478 | |
479 | pub fn join(data: &Vec<String>, sep: char) -> String { | |
480 | ||
481 | let mut list = String::new(); | |
482 | ||
483 | for item in data { | |
484 | if list.len() != 0 { list.push(sep); } | |
485 | list.push_str(item); | |
486 | } | |
487 | ||
488 | list | |
489 | } |