]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/tools.rs
src/client/http_client.rs: try to login
[proxmox-backup.git] / src / tools.rs
index ca64f64c214959ba94c6e9d1e9f69959e0ccd9a4..56a63f67e6975f65a01c033df6cdd107a0f1ad1f 100644 (file)
@@ -23,6 +23,8 @@ pub mod timer;
 pub mod wrapped_reader_stream;
 #[macro_use]
 pub mod common_regex;
+pub mod ticket;
+pub mod borrow;
 
 /// The `BufferedReader` trait provides a single function
 /// `buffered_read`. It returns a reference to an internal buffer. The
@@ -77,6 +79,10 @@ pub fn file_read_firstline<P: AsRef<Path>>(path: P) -> Result<String, std::io::E
     Ok(line)
 }
 
+pub fn file_get_contents<P: AsRef<Path>>(path: P) -> Result<Vec<u8>, std::io::Error> {
+    std::fs::read(path)
+}
+
 /// Atomically write a file. We first create a temporary file, which
 /// is then renamed.
 pub fn file_set_contents<P: AsRef<Path>>(
@@ -376,13 +382,55 @@ pub fn scandir<P, F>(
 
 pub fn get_hardware_address() -> Result<String, Error> {
 
-    static FILENAME: &str = "/etc/ssh/assh_host_rsa_key.pub";
-
-    let mut file = File::open(FILENAME)?;
-    let mut contents = Vec::new();
-    file.read_to_end(&mut contents)?;
+    static FILENAME: &str = "/etc/ssh/ssh_host_rsa_key.pub";
 
+    let contents = file_get_contents(FILENAME)?;
     let digest = md5::compute(contents);
 
     Ok(format!("{:0x}", digest))
 }
+
+pub fn digest_to_hex(digest: &[u8]) -> String {
+
+    const HEX_CHARS: &'static [u8; 16] = b"0123456789abcdef";
+
+    let mut buf = Vec::<u8>::with_capacity(digest.len()*2);
+
+    for i in 0..digest.len() {
+        buf.push(HEX_CHARS[(digest[i] >> 4) as usize]);
+        buf.push(HEX_CHARS[(digest[i] & 0xf) as usize]);
+    }
+
+    unsafe { String::from_utf8_unchecked(buf) }
+}
+
+pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> {
+    if digest1 != digest2 {
+       bail!("detected modified configuration - file changed by other user? Try again.");
+    }
+    Ok(())
+}
+
+/// Extract authentication cookie from cookie header.
+/// We assume cookie_name is already url encoded.
+pub fn extract_auth_cookie(cookie: &str, cookie_name: &str) -> Option<String> {
+
+    for pair in cookie.split(';') {
+
+        let (name, value) = match pair.find('=') {
+            Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()),
+            None => return None, // Cookie format error
+        };
+
+        if name == cookie_name {
+            use url::percent_encoding::percent_decode;
+            if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() {
+                return Some(value.into());
+            } else {
+                return None; // Cookie format error
+            }
+        }
+    }
+
+    None
+}