From 13596bfd4ec97638220a6fe5aee354d0ff1eec61 Mon Sep 17 00:00:00 2001
From: Darius Auding <Darius.auding@gmx.de>
Date: Wed, 19 Jul 2023 16:14:23 +0200
Subject: [PATCH] fix cargo clippy warnings

---
 core/http/src/handlers/handler.rs             | 26 +++++++++----------
 core/http/src/handling/request/form_utils.rs  |  2 +-
 .../{response.rs => build_and_write.rs}       |  0
 .../response/cookie_management/cookie.rs      |  2 +-
 core/http/src/handling/response/mod.rs        |  2 +-
 core/http/src/utils/url_utils/uri.rs          | 13 ++++------
 core/http/src/utils/urlencoded/datatypes.rs   | 20 +++++++++++++-
 core/http/src/utils/urlencoded/endecode.rs    | 12 ++++++---
 core/http/src/utils/urlencoded/mod.rs         |  3 +++
 site/src/main.rs                              |  2 +-
 10 files changed, 52 insertions(+), 30 deletions(-)
 rename core/http/src/handling/response/{response.rs => build_and_write.rs} (100%)

diff --git a/core/http/src/handlers/handler.rs b/core/http/src/handlers/handler.rs
index f1847b2..fa5f75a 100644
--- a/core/http/src/handlers/handler.rs
+++ b/core/http/src/handlers/handler.rs
@@ -1,8 +1,8 @@
 use std::{io, path::PathBuf};
 
 use tokio::{
-    io::{AsyncBufReadExt, AsyncReadExt, BufReader, AsyncWriteExt},
-    net::TcpStream, stream,
+    io::{AsyncBufReadExt, AsyncReadExt, BufReader},
+    net::TcpStream,
 };
 use tokio_native_tls::{TlsStream, TlsAcceptor};
 
@@ -215,14 +215,14 @@ fn error_occured_when_writing(e: io::Error) {
     eprintln!("\x1b[31mError {e} occured when trying to write answer to TCP-Stream for Client, aborting\x1b[0m");
 }
 
-async fn redirect_to_secure(mut stream: TcpStream) {
-    let resp = Response {
-        cookies: None,
-        status: Some(Status::MovedPermanently),
-        headers: vec!["Location: https://127.0.0.1".to_string()],
-        body: Box::new("")
-    }.build(None);
-    if let Err(e) = stream.write_all(&resp).await {
-        error_occured_when_writing(e);
-    }
-}
+// async fn redirect_to_secure(mut stream: TcpStream) {
+//     let resp = Response {
+//         cookies: None,
+//         status: Some(Status::MovedPermanently),
+//         headers: vec!["Location: https://127.0.0.1".to_string()],
+//         body: Box::new("")
+//     }.build(None);
+//     if let Err(e) = stream.write_all(&resp).await {
+//         error_occured_when_writing(e);
+//     }
+// }
diff --git a/core/http/src/handling/request/form_utils.rs b/core/http/src/handling/request/form_utils.rs
index 67ada47..cc8999d 100644
--- a/core/http/src/handling/request/form_utils.rs
+++ b/core/http/src/handling/request/form_utils.rs
@@ -143,7 +143,7 @@ impl Request {
                     let Some(thing) = keymap.get_mut(&key) else {
                         continue;
                     };
-                    *thing = Ok(value.into());
+                    *thing = Ok(value);
                 }
             }
             Mime::MultipartFormData => {
diff --git a/core/http/src/handling/response/response.rs b/core/http/src/handling/response/build_and_write.rs
similarity index 100%
rename from core/http/src/handling/response/response.rs
rename to core/http/src/handling/response/build_and_write.rs
diff --git a/core/http/src/handling/response/cookie_management/cookie.rs b/core/http/src/handling/response/cookie_management/cookie.rs
index 8234ab4..6175266 100644
--- a/core/http/src/handling/response/cookie_management/cookie.rs
+++ b/core/http/src/handling/response/cookie_management/cookie.rs
@@ -102,7 +102,7 @@ impl std::fmt::Display for Cookie {
         if let Some(same_site) = &self.same_site {
             appendix += &format!("; {}", same_site);
             if !self.secure && *same_site == SameSite::None {
-                appendix += &format!("; Secure");
+                appendix += "; Secure";
             }
         }
         if let Some(expires) = &self.expires {
diff --git a/core/http/src/handling/response/mod.rs b/core/http/src/handling/response/mod.rs
index 535eaa8..9233b38 100644
--- a/core/http/src/handling/response/mod.rs
+++ b/core/http/src/handling/response/mod.rs
@@ -1,6 +1,6 @@
+mod build_and_write;
 mod cookie_management;
 mod datatypes;
-mod response;
 mod status;
 mod traits;
 
diff --git a/core/http/src/utils/url_utils/uri.rs b/core/http/src/utils/url_utils/uri.rs
index b9e6939..6b8146b 100644
--- a/core/http/src/utils/url_utils/uri.rs
+++ b/core/http/src/utils/url_utils/uri.rs
@@ -7,10 +7,7 @@ use super::datatypes::{ParseUriError, RawUri, Uri, UriError};
 impl Uri {
     pub fn new(parts: Vec<&str>) -> Self {
         Self {
-            parts: parts
-                .into_iter()
-                .map(|part| UrlEncodeData::from_raw(part))
-                .collect(),
+            parts: parts.into_iter().map(UrlEncodeData::from_raw).collect(),
         }
     }
 }
@@ -23,11 +20,11 @@ impl RawUri {
             raw_string: "/".to_owned() + &parts.join("/"),
         };
         for part in parts {
-            if part.starts_with("<") && part.ends_with("..>") {
+            if part.starts_with('<') && part.ends_with("..>") {
                 result.infinte_end = true;
                 break;
             }
-            if part.starts_with("<") && part.ends_with(">") {
+            if part.starts_with('<') && part.ends_with('>') {
                 result.parts.push(RawUriElement::Variable);
                 continue;
             }
@@ -114,11 +111,11 @@ impl FromStr for RawUri {
             if part.is_empty() {
                 continue;
             }
-            if part.starts_with("<") && part.ends_with("..>") {
+            if part.starts_with('<') && part.ends_with("..>") {
                 result.infinte_end = true;
                 break;
             }
-            if part.starts_with("<") && part.ends_with(">") {
+            if part.starts_with('<') && part.ends_with('>') {
                 result.parts.push(RawUriElement::Variable);
                 continue;
             }
diff --git a/core/http/src/utils/urlencoded/datatypes.rs b/core/http/src/utils/urlencoded/datatypes.rs
index d48e02b..3207955 100644
--- a/core/http/src/utils/urlencoded/datatypes.rs
+++ b/core/http/src/utils/urlencoded/datatypes.rs
@@ -13,6 +13,24 @@ pub struct UrlEncodeData {
     pub(crate) raw_string: Option<String>,
 }
 
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
+pub enum UrlEncodeError {
+    NonHexAfterPercent,
+}
+
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub struct ParseUrlEncodeError {
+    pub inner: UrlEncodeError,
+}
+
+impl std::fmt::Display for ParseUrlEncodeError {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{:?}", self)
+    }
+}
+
+impl std::error::Error for ParseUrlEncodeError {}
+
 impl UrlEncodeData {
     /// Generates a [UrlEncodeData] from any raw data that can be a slice of [u8]
     pub fn from_raw<T: AsRef<[u8]>>(raw: T) -> Self {
@@ -27,7 +45,7 @@ impl UrlEncodeData {
     /// # Errors
     ///
     /// errors if the encoded data is wrongly encoded -> %<invalid_character>
-    pub fn from_encoded(encoded: &str) -> Result<Self, ()> {
+    pub fn from_encoded(encoded: &str) -> super::UriParseResult<Self> {
         Ok(Self {
             encoded: encoded.to_owned(),
             raw: encoded.decode()?,
diff --git a/core/http/src/utils/urlencoded/endecode.rs b/core/http/src/utils/urlencoded/endecode.rs
index 8dd45d6..8a77253 100644
--- a/core/http/src/utils/urlencoded/endecode.rs
+++ b/core/http/src/utils/urlencoded/endecode.rs
@@ -1,3 +1,5 @@
+use super::{datatypes::ParseUrlEncodeError, UriParseResult};
+
 /// Base of the HexaDecimal Number system
 static BASE16_HEXA_DECIMAL: u8 = 0x10;
 /// Highest possible Value per digit
@@ -15,7 +17,7 @@ pub trait DeCodable {
     ///
     /// # Errors
     /// Errors if the encoding isn't right
-    fn decode(&self) -> Result<Vec<u8>, ()>;
+    fn decode(&self) -> UriParseResult<Vec<u8>>;
 }
 
 impl<T: AsRef<[u8]>> EnCodable for T {
@@ -44,7 +46,7 @@ impl EnCodable for [u8] {
     }
 }
 impl DeCodable for &str {
-    fn decode(&self) -> Result<Vec<u8>, ()> {
+    fn decode(&self) -> UriParseResult<Vec<u8>> {
         let mut first = true;
         let mut result = Vec::with_capacity(self.len());
 
@@ -55,7 +57,7 @@ impl DeCodable for &str {
                 continue;
             }
             let Ok(char) = u8::from_str_radix(i[0..=1].as_ref(), BASE16_HEXA_DECIMAL.into()) else {
-                    return Err(());
+                    return Err(ParseUrlEncodeError { inner: super::datatypes::UrlEncodeError::NonHexAfterPercent });
             };
             result.push(char);
             result.extend_from_slice(i[2..].as_bytes());
@@ -97,7 +99,9 @@ mod test {
             .unwrap()
         );
         assert_eq!(
-            Err(()),
+            Err(crate::utils::urlencoded::datatypes::ParseUrlEncodeError {
+                inner: crate::utils::urlencoded::datatypes::UrlEncodeError::NonHexAfterPercent
+            }),
             "Darius%2iis%20the%20biggest%20genius%2FGenie%2FHuman%20extraordin%C3%A4ire".decode()
         );
         assert_eq!(
diff --git a/core/http/src/utils/urlencoded/mod.rs b/core/http/src/utils/urlencoded/mod.rs
index 3145200..bf5f292 100644
--- a/core/http/src/utils/urlencoded/mod.rs
+++ b/core/http/src/utils/urlencoded/mod.rs
@@ -1,4 +1,7 @@
 mod datatypes;
 mod endecode;
+use std::result;
+
+type UriParseResult<T> = result::Result<T, datatypes::ParseUrlEncodeError>;
 pub use datatypes::UrlEncodeData;
 pub use endecode::{DeCodable, EnCodable};
diff --git a/site/src/main.rs b/site/src/main.rs
index 22e7900..014d33a 100644
--- a/site/src/main.rs
+++ b/site/src/main.rs
@@ -105,7 +105,7 @@ async fn main() {
         rank: 0,
     };
 
-    http::build("127.0.0.1:8000")
+    http::build("127.0.0.1:8080")
         .await
         .mount("/", vec![fileserver, post_test, static_hi])
         .mount("/post/", vec![post_test])
-- 
GitLab