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