[pbs-devel] [PATCH proxmox-backup rebase 07/15] move normalize_uri_path and extract_cookie to pbs-server crate

Dietmar Maurer dietmar at proxmox.com
Mon Sep 20 11:13:32 CEST 2021


---
 pbs-server/Cargo.toml   |  1 +
 pbs-server/src/lib.rs   | 47 +++++++++++++++++++++++++++++++++++++++++
 src/server/auth.rs      |  5 ++---
 src/server/h2service.rs |  4 ++--
 src/server/rest.rs      |  6 +++---
 src/tools/mod.rs        | 46 ----------------------------------------
 6 files changed, 55 insertions(+), 54 deletions(-)

diff --git a/pbs-server/Cargo.toml b/pbs-server/Cargo.toml
index 9e93fb0e..9f76f720 100644
--- a/pbs-server/Cargo.toml
+++ b/pbs-server/Cargo.toml
@@ -15,6 +15,7 @@ lazy_static = "1.4"
 libc = "0.2"
 log = "0.4"
 nix = "0.19.1"
+percent-encoding = "2.1"
 serde = { version = "1.0", features = [] }
 serde_json = "1.0"
 tokio = { version = "1.6", features = ["signal", "process"] }
diff --git a/pbs-server/src/lib.rs b/pbs-server/src/lib.rs
index 069d80b4..9107a03f 100644
--- a/pbs-server/src/lib.rs
+++ b/pbs-server/src/lib.rs
@@ -88,3 +88,50 @@ pub fn socketpair() -> Result<(Fd, Fd), Error> {
     Ok((Fd(pa), Fd(pb)))
 }
 
+
+/// Extract a specific cookie from cookie header.
+/// We assume cookie_name is already url encoded.
+pub fn extract_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 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
+}
+
+/// normalize uri path
+///
+/// Do not allow ".", "..", or hidden files ".XXXX"
+/// Also remove empty path components
+pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> {
+    let items = path.split('/');
+
+    let mut path = String::new();
+    let mut components = vec![];
+
+    for name in items {
+        if name.is_empty() {
+            continue;
+        }
+        if name.starts_with('.') {
+            bail!("Path contains illegal components.");
+        }
+        path.push('/');
+        path.push_str(name);
+        components.push(name);
+    }
+
+    Ok((path, components))
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 3e2d0c89..d7fbf511 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -6,10 +6,9 @@ use std::sync::Arc;
 use pbs_tools::ticket::{self, Ticket};
 use pbs_config::{token_shadow, CachedUserInfo};
 use pbs_api_types::{Authid, Userid};
-use pbs_server::{ApiAuth, AuthError};
+use pbs_server::{ApiAuth, AuthError, extract_cookie};
 
 use crate::auth_helpers::*;
-use crate::tools;
 
 use hyper::header;
 use percent_encoding::percent_decode_str;
@@ -33,7 +32,7 @@ impl UserApiAuth {
     fn extract_auth_data(headers: &http::HeaderMap) -> Option<AuthData> {
         if let Some(raw_cookie) = headers.get(header::COOKIE) {
             if let Ok(cookie) = raw_cookie.to_str() {
-                if let Some(ticket) = tools::extract_cookie(cookie, "PBSAuthCookie") {
+                if let Some(ticket) = extract_cookie(cookie, "PBSAuthCookie") {
                     let csrf_token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) {
                         Some(Ok(v)) => Some(v.to_owned()),
                         _ => None,
diff --git a/src/server/h2service.rs b/src/server/h2service.rs
index bc9561d3..9b473bbf 100644
--- a/src/server/h2service.rs
+++ b/src/server/h2service.rs
@@ -11,9 +11,9 @@ use hyper::{Body, Request, Response, StatusCode};
 use proxmox::api::{ApiResponseFuture, HttpError, Router, RpcEnvironment};
 use proxmox::http_err;
 
+use pbs_server::normalize_uri_path;
 use pbs_server::formatter::*;
 
-use crate::tools;
 use crate::server::WorkerTask;
 
 /// Hyper Service implementation to handle stateful H2 connections.
@@ -44,7 +44,7 @@ impl <E: RpcEnvironment + Clone> H2Service<E> {
 
         let method = parts.method.clone();
 
-        let (path, components) = match tools::normalize_uri_path(parts.uri.path()) {
+        let (path, components) = match normalize_uri_path(parts.uri.path()) {
             Ok((p,c)) => (p, c),
             Err(err) => return future::err(http_err!(BAD_REQUEST, "{}", err)).boxed(),
         };
diff --git a/src/server/rest.rs b/src/server/rest.rs
index e1a081b6..a47f0b87 100644
--- a/src/server/rest.rs
+++ b/src/server/rest.rs
@@ -36,13 +36,13 @@ use pbs_tools::stream::AsyncReaderStream;
 use pbs_api_types::{Authid, Userid};
 use pbs_server::{
     ApiConfig, FileLogger, FileLogOptions, AuthError, RestEnvironment, CompressionMethod,
+    extract_cookie, normalize_uri_path,
 };
 use pbs_server::formatter::*;
 
 use pbs_config::CachedUserInfo;
 
 use crate::auth_helpers::*;
-use crate::tools;
 
 extern "C" {
     fn tzset();
@@ -645,7 +645,7 @@ async fn handle_static_file_download(
 
 fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
     if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
-        return tools::extract_cookie(cookie, "PBSLangCookie");
+        return extract_cookie(cookie, "PBSLangCookie");
     }
     None
 }
@@ -669,7 +669,7 @@ async fn handle_request(
 ) -> Result<Response<Body>, Error> {
     let (parts, body) = req.into_parts();
     let method = parts.method.clone();
-    let (path, components) = tools::normalize_uri_path(parts.uri.path())?;
+    let (path, components) = normalize_uri_path(parts.uri.path())?;
 
     let comp_len = components.len();
 
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
index f2576b08..5dc129f0 100644
--- a/src/tools/mod.rs
+++ b/src/tools/mod.rs
@@ -49,27 +49,6 @@ pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> {
     Ok(())
 }
 
-/// Extract a specific cookie from cookie header.
-/// We assume cookie_name is already url encoded.
-pub fn extract_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 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
-}
 
 /// Detect modified configuration files
 ///
@@ -81,31 +60,6 @@ pub fn detect_modified_configuration_file(digest1: &[u8;32], digest2: &[u8;32])
     Ok(())
 }
 
-/// normalize uri path
-///
-/// Do not allow ".", "..", or hidden files ".XXXX"
-/// Also remove empty path components
-pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> {
-    let items = path.split('/');
-
-    let mut path = String::new();
-    let mut components = vec![];
-
-    for name in items {
-        if name.is_empty() {
-            continue;
-        }
-        if name.starts_with('.') {
-            bail!("Path contains illegal components.");
-        }
-        path.push('/');
-        path.push_str(name);
-        components.push(name);
-    }
-
-    Ok((path, components))
-}
-
 /// An easy way to convert types to Any
 ///
 /// Mostly useful to downcast trait objects (see RpcEnvironment).
-- 
2.30.2






More information about the pbs-devel mailing list