]> git.ipfire.org Git - thirdparty/pdns.git/commitdiff
Modularize: split out misc.rs for general stuff
authorOtto Moerbeek <otto.moerbeek@open-xchange.com>
Fri, 31 Jan 2025 16:22:41 +0000 (17:22 +0100)
committerOtto Moerbeek <otto.moerbeek@open-xchange.com>
Tue, 11 Feb 2025 15:28:22 +0000 (16:28 +0100)
18 files changed:
pdns/recursordist/rec-main.cc
pdns/recursordist/rec-web-stubs.hh
pdns/recursordist/settings/cxxsupport.cc
pdns/recursordist/settings/rust-bridge-in.rs
pdns/recursordist/settings/rust-preamble-in.rs
pdns/recursordist/settings/rust/.gitignore
pdns/recursordist/settings/rust/Cargo.lock
pdns/recursordist/settings/rust/Cargo.toml
pdns/recursordist/settings/rust/Makefile.am
pdns/recursordist/settings/rust/build.rs
pdns/recursordist/settings/rust/build_settings
pdns/recursordist/settings/rust/src/bridge.hh
pdns/recursordist/settings/rust/src/bridge.rs
pdns/recursordist/settings/rust/src/misc.rs [new file with mode: 0644]
pdns/recursordist/settings/rust/src/web.rs
pdns/recursordist/ws-recursor.cc
pdns/recursordist/ws-recursor.hh
pdns/webserver.hh

index b258792664d2be16a04ed9f287d49aac68a462d3..9e3ebb976569476b124ebfd9f34eae9d4a504582 100644 (file)
@@ -274,8 +274,6 @@ int RecThreadInfo::runThreads(Logr::log_t log)
     }
 
     if (::arg().mustDo("webserver")) {
-      extern void serveRustWeb();
-      cerr << "CALL serveRustWeb" << endl;
       serveRustWeb();
     }
 
@@ -358,13 +356,8 @@ int RecThreadInfo::runThreads(Logr::log_t log)
     info.start(currentThreadId, "web+stat", cpusMap, log);
 
     if (::arg().mustDo("webserver")) {
-      extern void serveRustWeb();
-      cerr << "WS is CALLED " << endl;
       serveRustWeb();
     }
-    else {
-      cerr << "WS is FALSE " << endl;
-    }
     for (auto& tInfo : RecThreadInfo::infos()) {
       tInfo.thread.join();
       if (tInfo.exitCode != 0) {
index 316d84dbabc894088f9733f1ac03095342a7aeec..60a2d3938bfcdbcd9977ce7e81b6428ab9bcd656 100644 (file)
@@ -4,6 +4,9 @@ namespace pdns::rust::web::rec
 #define WRAPPER(A) \
   void A(const Request& /* unused */, Response& /* unused */) {}
 
+class Request;
+class Response;
+
 WRAPPER(apiDiscovery)
 WRAPPER(apiDiscoveryV1)
 WRAPPER(apiServer)
index ec94e9121c8c725e524819a76047e91eed34db1e..e41ba09db502ed0b3f2504a9a324066abd07f92e 100644 (file)
@@ -42,6 +42,7 @@
 #include "iputils.hh"
 #include "bridge.hh"
 #include "settings/rust/web.rs.h"
+#include "settings/rust/misc.rs.h"
 
 ::rust::Vec<::rust::String> pdns::settings::rec::getStrings(const std::string& name)
 {
@@ -1441,24 +1442,7 @@ pdns::settings::rec::YamlSettingsStatus pdns::settings::rec::tryReadYAML(const s
   return yamlstatus;
 }
 
-uint16_t pdns::rust::settings::rec::qTypeStringToCode(::rust::Str str)
-{
-  std::string tmp(str.data(), str.length());
-  return QType::chartocode(tmp.c_str());
-}
-
-bool pdns::rust::settings::rec::isValidHostname(::rust::Str str)
-{
-  try {
-    auto name = DNSName(string(str));
-    return name.isHostname();
-  }
-  catch (...) {
-    return false;
-  }
-}
-
-namespace pdns::rust::web::rec
+namespace pdns::rust::misc
 {
 
 template <typename M>
@@ -1478,7 +1462,25 @@ template <typename M>
 
 template class Wrapper<::NetmaskGroup>;
 template class Wrapper<::ComboAddress>;
-  //template class Wrapper<std::shared_ptr<::Logr::Logger>>;
+
+uint16_t qTypeStringToCode(::rust::Str str)
+{
+  std::string tmp(str.data(), str.length());
+  return QType::chartocode(tmp.c_str());
+}
+
+bool isValidHostname(::rust::Str str)
+{
+  try {
+    auto name = DNSName(string(str));
+    return name.isHostname();
+  }
+  catch (...) {
+    return false;
+  }
+}
+
+void findBetterSolution(const std::unique_ptr<CredentialsHolder>& /* x */){};
 
 std::unique_ptr<ComboAddress> comboaddress(::rust::Str str)
 {
@@ -1490,7 +1492,7 @@ bool matches(const std::unique_ptr<NetmaskGroup>& nmg, const std::unique_ptr<Com
   return nmg->get().match(address->get());
 }
 
-void log(const std::shared_ptr<Logger>& logger, pdns::rust::web::rec::Priority log_level, ::rust::Str msg, const ::rust::Vec<KeyValue>& values)
+  void log(const std::shared_ptr<Logger>& logger, pdns::rust::misc::Priority log_level, ::rust::Str msg, const ::rust::Vec<KeyValue>& values)
 {
   auto log = logger;
   for (const auto& [key, value] : values) {
@@ -1499,7 +1501,7 @@ void log(const std::shared_ptr<Logger>& logger, pdns::rust::web::rec::Priority l
   log->info(static_cast<Logr::Priority>(log_level), std::string(msg));
 }
 
-void error(const std::shared_ptr<Logger>& logger, pdns::rust::web::rec::Priority log_level, ::rust::Str error, ::rust::Str msg, const ::rust::Vec<KeyValue>& values)
+  void error(const std::shared_ptr<Logger>& logger, pdns::rust::misc::Priority log_level, ::rust::Str error, ::rust::Str msg, const ::rust::Vec<KeyValue>& values)
 {
   auto log = logger;
   for (const auto& [key, value] : values) {
index 731cc15a8584f9ab39d846c2cdc549f24491ccb6..176ebad2ee391015106f0b635eed1014ccd58132 100644 (file)
@@ -310,8 +310,8 @@ pub struct IncomingTLS {
     certificate: String,
     #[serde(default, skip_serializing_if = "crate::is_default")]
     key: String,
-    #[serde(default, skip_serializing_if = "crate::is_default")]
-    password: String,
+    // #[serde(default, skip_serializing_if = "crate::is_default")]
+    // password: String, Not currently supported, as rusttls does not support this out of the box
 }
 #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
 #[serde(deny_unknown_fields)]
@@ -410,8 +410,3 @@ extern "Rust" {
     fn api_delete_zones(file: &str) -> Result<()>;
 }
 
-unsafe extern "C++" {
-    include!("bridge.hh");
-    fn qTypeStringToCode(name: &str) -> u16;
-    fn isValidHostname(name: &str) -> bool;
-}
index ee611f1533ef94190470cca1f9e327c1ecf131a3..d3758f6779cf5ce35aa23eb1266268b7ef977c35 100644 (file)
@@ -30,6 +30,8 @@ use helpers::*;
 mod bridge;
 use bridge::*;
 
+mod misc;
+
 mod web; // leaving this out causes link issues
 
 // Suppresses "Deserialize unused" warning
index d31bd391e756cba5c22b74d555fb51c77854ad9e..e9e427e1cd87dbbbc252211b1b60b8d0afccaf9e 100644 (file)
@@ -4,5 +4,6 @@
 /cxx.h
 /lib.rs.h
 /web.rs.h
+/misc.rs.h
 src/lib.rs
 .dir-locals.el
index 4eca9bc1136e9000bdfd846a88ea2f6ff4117e46..68014e7988f1fc78c7145db2ceb1726b9559f3ab 100644 (file)
@@ -457,7 +457,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "8f287924602bf649d949c63dc8ac8b235fa5387d394020705b80c4eb597ce5b8"
 dependencies = [
  "once_cell",
- "ring",
  "rustls-pki-types",
  "rustls-webpki",
  "subtle",
index c68288d30301d2f139c5662c8caa8914e18ef0a4..01b5e803427e56ed3bf18599a7d2e642b62ecd03 100644 (file)
@@ -22,11 +22,12 @@ hyper-util = { version = "0.1", features = ["tokio"]}
 bytes = "1.8"
 form_urlencoded = "1.2"
 hyper-rustls = { version = "0.27",  default-features = false }
-rustls = { version = "0.23", default-features = false, features = ["ring"] }
+rustls = { version = "0.23", default-features = false, features = [] }
 rustls-pemfile = "2.2"
 pki-types = { package = "rustls-pki-types", version = "1.10" }
 tokio-rustls = { version = "0.26", default-features = false }
 uuid = { version = "1.12.1", features = ["v4"] }
+
 [build-dependencies]
 cxx-build = "1.0"
 
index 6ade7921d08b1f5e1fe720f25df932efb2d4e795..504518913675f1a8b0092925bc3dedfcd29fd840 100644 (file)
@@ -3,20 +3,30 @@ CARGO ?= cargo
 all install: libsettings.a
 
 EXTRA_DIST = \
-       Cargo.toml \
        Cargo.lock \
+       Cargo.toml \
        build.rs \
        src/bridge.rs \
        src/helpers.rs \
+        src/misc.rs \
         src/web.rs
 
 # should actually end up in a target specific dir...
-libsettings.a lib.rs.h web.rs.h: src/web.rs src/bridge.rs src/lib.rs src/helpers.rs Cargo.toml Cargo.lock build.rs
+libsettings.a lib.rs.h web.rs.h misc.rs.h: \
+       Cargo.lock \
+       Cargo.toml \
+       build.rs \
+       src/bridge.rs \
+       src/helpers.rs \
+       src/lib.rs \
+       src/misc.rs \
+       src/web.rs
        SYSCONFDIR=$(sysconfdir) NODCACHEDIRNOD=$(localstatedir)/nod NODCACHEDIRUDR=$(localstatedir)/udr $(CARGO) build --release $(RUST_TARGET) --target-dir=$(builddir)/target --manifest-path ${srcdir}/Cargo.toml
        cp target/$(RUSTC_TARGET_ARCH)/release/libsettings.a libsettings.a
        cp target/$(RUSTC_TARGET_ARCH)/cxxbridge/settings/src/lib.rs.h lib.rs.h
        cp target/$(RUSTC_TARGET_ARCH)/cxxbridge/settings/src/web.rs.h web.rs.h
+       cp target/$(RUSTC_TARGET_ARCH)/cxxbridge/settings/src/misc.rs.h misc.rs.h
        cp target/$(RUSTC_TARGET_ARCH)/cxxbridge/rust/cxx.h cxx.h
 
 clean-local:
-       rm -rf libsettings.a src/lib.rs lib.rs.h web.rs.h cxx.h target
+       rm -rf libsettings.a src/lib.rs lib.rs.h web.rs.h cxx.h misc.rs.h target
index cdf64ab167a52375ba6c9088632ba4367d70e706..21eb063a8d1a2dead9760b62c4c67d78a39b6a1c 100644 (file)
@@ -1,9 +1,13 @@
 fn main() {
-    let sources = vec!["src/lib.rs", "src/web.rs"];
+    let sources = vec!["src/lib.rs", "src/web.rs", "src/misc.rs"];
     cxx_build::bridges(sources)
         // .file("src/source.cc") Code callable from Rust is in ../cxxsupport.cc
         .flag_if_supported("-std=c++17")
         .flag("-Isrc")
         .flag("-I../../..")
         .compile("settings");
+
+    // lib.rs is genertated an take carte of by parent Makefile
+    println!("cargo:rerun-if-changed=src/misc.rs");
+    println!("cargo:rerun-if-changed=src/web.rs");
 }
index 34c6170de0b7e22bee80e1b85d583cefab26059b..073479a9da70ccff7aab5d2f33b7b814be1c9754 100755 (executable)
@@ -6,7 +6,6 @@
 
 $CARGO build --release $RUST_TARGET --target-dir=$builddir/target --manifest-path $srcdir/Cargo.toml
 
-
 cp -vp target/$RUSTC_TARGET_ARCH/release/libsettings.a $builddir/settings/rust/libsettings.a
 cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/settings/src/lib.rs.h $srcdir/lib.rs.h
 cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/settings/src/lib.rs.h $builddir/settings/rust/lib.rs.h
@@ -14,3 +13,5 @@ cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/rust/cxx.h $srcdir/cxx.h
 cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/rust/cxx.h $builddir/settings/rust/cxx.h
 cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/settings/src/web.rs.h $srcdir/web.rs.h
 cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/settings/src/web.rs.h $builddir/settings/rust/web.rs.h
+cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/settings/src/misc.rs.h $srcdir/misc.rs.h
+cp -vp target/$RUSTC_TARGET_ARCH/cxxbridge/settings/src/misc.rs.h $builddir/settings/rust/misc.rs.h
index 4c15177313d48eb2c4e8965e4e3da1446b7ce731..5afe3ef37ae29a4b3feacfe19de20383c79ba55b 100644 (file)
 #include "rust/cxx.h"
 #include "credentials.hh"
 
-namespace pdns::rust::settings::rec
-{
-uint16_t qTypeStringToCode(::rust::Str str);
-bool isValidHostname(::rust::Str str);
-void setThreadName(::rust::Str str);
-}
-
 class NetmaskGroup;
 union ComboAddress;
 namespace Logr
@@ -40,15 +33,11 @@ namespace Logr
 class Logger;
 }
 
-
-namespace pdns::rust::web::rec
-{
-using CredentialsHolder = ::CredentialsHolder;
-struct KeyValue;
-struct Request;
-struct Response;
-struct IncomingWSConfig;
+namespace pdns::rust::misc {
 enum class Priority : uint8_t;
+enum class LogLevel : uint8_t;
+using Logger = ::Logr::Logger;
+struct KeyValue;
 
 template <typename A>
 class Wrapper
@@ -68,9 +57,27 @@ public:
 private:
   std::unique_ptr<A> d_ptr;
 };
+
 using NetmaskGroup = Wrapper<::NetmaskGroup>;
 using ComboAddress = Wrapper<::ComboAddress>;
-using Logger = ::Logr::Logger;
+
+uint16_t qTypeStringToCode(::rust::Str str);
+bool isValidHostname(::rust::Str str);
+std::unique_ptr<pdns::rust::misc::ComboAddress> comboaddress(::rust::Str str);
+bool matches(const std::unique_ptr<NetmaskGroup>& nmg, const std::unique_ptr<ComboAddress>& address);
+std::shared_ptr<Logger> withValue(const std::shared_ptr<Logger>& logger, ::rust::Str key, ::rust::Str val);
+void log(const std::shared_ptr<Logger>& logger, Priority log_level, ::rust::Str msg, const ::rust::Vec<KeyValue>& values);
+void error(const std::shared_ptr<Logger>& logger, Priority log_level, ::rust::Str err, ::rust::Str msg, const ::rust::Vec<KeyValue>& values);
+}
+
+
+namespace pdns::rust::web::rec
+{
+using CredentialsHolder = ::CredentialsHolder;
+struct KeyValue;
+struct Request;
+struct Response;
+struct IncomingWSConfig;
 
 void apiServer(const Request& rustRequest, Response& rustResponse);
 void apiDiscovery(const Request& rustRequest, Response& rustResponse);
@@ -93,9 +100,4 @@ void apiServerSearchData(const Request& rustRequest, Response& rustResponse);
 void apiServerZoneDetailGET(const Request& rustRequest, Response& rustResponse);
 void apiServerZoneDetailPUT(const Request& rustRequest, Response& rustResponse);
 void apiServerZoneDetailDELETE(const Request& rustRequest, Response& rustResponse);
-std::unique_ptr<ComboAddress> comboaddress(::rust::Str str);
-bool matches(const std::unique_ptr<NetmaskGroup>& nmg, const std::unique_ptr<ComboAddress>& address);
-std::shared_ptr<Logger> withValue(const std::shared_ptr<Logger>& logger, ::rust::Str key, ::rust::Str val);
-void log(const std::shared_ptr<Logger>& logger, Priority log_level, ::rust::Str msg, const ::rust::Vec<KeyValue>& values);
-void error(const std::shared_ptr<Logger>& logger, Priority log_level, ::rust::Str err, ::rust::Str msg, const ::rust::Vec<KeyValue>& values);
 }
index e67931d464c6fdd16b3d136be6efd85c71122140..701bdc4f993077f92671c473d26e24d0382ab915 100644 (file)
@@ -31,6 +31,7 @@ use std::sync::Mutex;
 use crate::helpers::OVERRIDE_TAG;
 use crate::recsettings::{self, *};
 use crate::{Merge, ValidationError};
+use crate::misc::rustmisc;
 
 impl Default for ForwardZone {
     fn default() -> Self {
@@ -123,9 +124,9 @@ fn is_port_number(str: &str) -> bool {
 
 pub fn validate_socket_address_or_name(field: &str, val: &String) -> Result<(), ValidationError> {
     let sa = validate_socket_address(field, val);
-    if sa.is_err() && !isValidHostname(val) {
+    if sa.is_err() && !rustmisc::isValidHostname(val) {
         let parts: Vec<&str> = val.split(':').collect();
-        if parts.len() != 2 || !isValidHostname(parts[0]) || !is_port_number(parts[1]) {
+        if parts.len() != 2 || !rustmisc::isValidHostname(parts[0]) || !is_port_number(parts[1]) {
             let msg = format!(
                 "{}: value `{}' is not an IP, IP:port, name or name:port combination",
                 field, val
@@ -137,7 +138,7 @@ pub fn validate_socket_address_or_name(field: &str, val: &String) -> Result<(),
 }
 
 fn validate_qtype(field: &str, val: &String) -> Result<(), ValidationError> {
-    let code = qTypeStringToCode(val);
+    let code = rustmisc::qTypeStringToCode(val);
     if code == 0 {
         let msg = format!("{}: value `{}' is not a qtype", field, val);
         return Err(ValidationError { msg });
diff --git a/pdns/recursordist/settings/rust/src/misc.rs b/pdns/recursordist/settings/rust/src/misc.rs
new file mode 100644 (file)
index 0000000..87118cb
--- /dev/null
@@ -0,0 +1,47 @@
+#[cxx::bridge(namespace = "pdns::rust::misc")]
+pub mod rustmisc {
+
+    pub enum LogLevel {
+        None,
+        Normal,
+        Detailed,
+    }
+    enum Priority {
+        Absent = 0,
+        Alert = 1,
+        Critical = 2,
+        Error = 3,
+        Warning = 4,
+        Notice = 5,
+        Info = 6,
+        Debug = 7,
+    }
+    struct KeyValue {
+        key: String,
+        value: String,
+    }
+
+    extern "C++" {
+        type NetmaskGroup;
+        type ComboAddress;
+        type Logger;
+    }
+
+    unsafe extern "C++" {
+        include!("bridge.hh");
+        fn qTypeStringToCode(name: &str) -> u16;
+        fn isValidHostname(name: &str) -> bool;
+        fn comboaddress(address: &str) -> UniquePtr<ComboAddress>;
+        fn matches(nmg: &UniquePtr<NetmaskGroup>, address: &UniquePtr<ComboAddress>) -> bool; // match is a keyword
+        fn withValue(logger: &SharedPtr<Logger>, key: &str, val: &str) -> SharedPtr<Logger>;
+        fn log(logger: &SharedPtr<Logger>, prio: Priority, msg: &str, values: &Vec<KeyValue>);
+        fn error(
+            logger: &SharedPtr<Logger>,
+            prio: Priority,
+            err: &str,
+            msg: &str,
+            values: &Vec<KeyValue>,
+        );
+   }
+}
+
index b848166c7b1839db3b8dcd97f8d8619996fbb3c4..fa95835a54bb6c54874cfb7105429916aa57fc29 100644 (file)
@@ -28,6 +28,8 @@ use tokio::net::TcpListener;
 use tokio::runtime::Builder;
 use tokio::task::JoinSet;
 
+use crate::misc::rustmisc;
+
 type GenericError = Box<dyn std::error::Error + Send + Sync>;
 type MyResult<T> = std::result::Result<T, GenericError>;
 type BoxBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;
@@ -88,11 +90,11 @@ fn nonapi_wrapper(
 ) {
     let auth_ok = compare_authorization(ctx, reqheaders);
     if !auth_ok {
-        rustweb::log(
+        rustmisc::log(
             request.logger,
             rustweb::Priority::Debug,
             "Authentication failed",
-            &vec![rustweb::KeyValue {
+            &vec![rustmisc::KeyValue {
                 key: "urlpath".to_string(),
                 value: request.uri.to_owned(),
             }],
@@ -122,11 +124,11 @@ fn file_wrapper(
 ) {
     let auth_ok = compare_authorization(ctx, reqheaders);
     if !auth_ok {
-        rustweb::log(
+        rustmisc::log(
             request.logger,
             rustweb::Priority::Debug,
             "Authentication failed",
-            &vec![rustweb::KeyValue {
+            &vec![rustmisc::KeyValue {
                 key: "urlpath".to_string(),
                 value: request.uri.to_owned(),
             }],
@@ -153,11 +155,11 @@ fn api_wrapper(
         header::HeaderValue::from_static("*"),
     );
     if ctx.api_ch.is_null() {
-        rustweb::log(
+        rustmisc::log(
             logger,
             rustweb::Priority::Error,
             "Authentication failed, API Key missing in config",
-            &vec![rustweb::KeyValue {
+            &vec![rustmisc::KeyValue {
                 key: "urlpath".to_string(),
                 value: request.uri.to_owned(),
             }],
@@ -185,11 +187,11 @@ fn api_wrapper(
     if !auth_ok && allow_password {
         auth_ok = compare_authorization(ctx, reqheaders);
         if !auth_ok {
-            rustweb::log(
+            rustmisc::log(
                 logger,
                 rustweb::Priority::Debug,
                 "Authentication failed",
-                &vec![rustweb::KeyValue {
+                &vec![rustmisc::KeyValue {
                     key: "urlpath".to_string(),
                     value: request.uri.to_owned(),
                 }],
@@ -199,11 +201,11 @@ fn api_wrapper(
         }
     }
     if !auth_ok {
-        rustweb::log(
+        rustmisc::log(
             logger,
             rustweb::Priority::Error,
             "Authentication failed",
-            &vec![rustweb::KeyValue {
+            &vec![rustmisc::KeyValue {
                 key: "urlpath".to_string(),
                 value: request.uri.to_owned(),
             }],
@@ -250,9 +252,9 @@ struct Context {
     urls: Vec<String>,
     password_ch: cxx::UniquePtr<rustweb::CredentialsHolder>,
     api_ch: cxx::UniquePtr<rustweb::CredentialsHolder>,
-    acl: cxx::UniquePtr<rustweb::NetmaskGroup>,
-    logger: cxx::SharedPtr<rustweb::Logger>,
-    loglevel: rustweb::LogLevel,
+    acl: cxx::UniquePtr<rustmisc::NetmaskGroup>,
+    logger: cxx::SharedPtr<rustmisc::Logger>,
+    loglevel: rustmisc::LogLevel,
 }
 
 // Serve a file
@@ -272,16 +274,16 @@ fn file(
         .iter()
         .position(|x| String::from("/") + x == uripath);
     if pos.is_none() {
-        rustweb::log(
+        rustmisc::log(
             request.logger,
             rustweb::Priority::Debug,
             "not found",
             &vec![
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "method".to_string(),
                     value: method.to_string(),
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "uripath".to_string(),
                     value: uripath.to_string(),
                 },
@@ -294,16 +296,16 @@ fn file(
         // Return 404 not found response.
         response.status = StatusCode::NOT_FOUND.as_u16();
         response.body = NOTFOUND.to_vec();
-        rustweb::log(
+        rustmisc::log(
             request.logger,
             rustweb::Priority::Debug,
             "not found case 2",
             &vec![
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "method".to_string(),
                     value: method.to_string(),
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "uripath".to_string(),
                     value: uripath.to_string(),
                 },
@@ -407,7 +409,7 @@ fn matcher(
 fn collect_options(
     path: &str,
     response: &mut rustweb::Response,
-    my_logger: &cxx::SharedPtr<rustweb::Logger>,
+    my_logger: &cxx::SharedPtr<rustmisc::Logger>,
 ) {
     let mut methods = vec![];
     for method in [Method::GET, Method::POST, Method::PUT, Method::DELETE] {
@@ -465,17 +467,17 @@ fn collect_options(
     });
 }
 
-fn log_request(loglevel: rustweb::LogLevel, request: &rustweb::Request, remote: SocketAddr) {
-    if loglevel != rustweb::LogLevel::Detailed {
+fn log_request(loglevel: rustmisc::LogLevel, request: &rustweb::Request, remote: SocketAddr) {
+    if loglevel != rustmisc::LogLevel::Detailed {
         return;
     }
     let body = std::str::from_utf8(&request.body).unwrap_or("error: body is not utf8");
     let mut vec = vec![
-        rustweb::KeyValue {
+        rustmisc::KeyValue {
             key: "remote".to_string(),
             value: remote.to_string(),
         },
-        rustweb::KeyValue {
+        rustmisc::KeyValue {
             key: "body".to_string(),
             value: body.to_string(),
         },
@@ -490,34 +492,34 @@ fn log_request(loglevel: rustweb::LogLevel, request: &rustweb::Request, remote:
         let snippet = var.key.to_owned() + "=" + &var.value;
         str.push_str(&snippet);
     }
-    vec.push(rustweb::KeyValue {
+    vec.push(rustmisc::KeyValue {
         key: "getVars".to_string(),
         value: str.to_string(),
     });
-    rustweb::log(
+    rustmisc::log(
         request.logger,
-        rustweb::Priority::Info,
+        rustmisc::Priority::Info,
         "Request details",
         &vec,
     );
 }
 
 fn log_response(
-    loglevel: rustweb::LogLevel,
-    logger: &cxx::SharedPtr<rustweb::Logger>,
+    loglevel: rustmisc::LogLevel,
+    logger: &cxx::SharedPtr<rustmisc::Logger>,
     response: &rustweb::Response,
     remote: SocketAddr,
 ) {
-    if loglevel != rustweb::LogLevel::Detailed {
+    if loglevel != rustmisc::LogLevel::Detailed {
         return;
     }
     let body = std::str::from_utf8(&response.body).unwrap_or("error: body is not utf8");
     let mut vec = vec![
-        rustweb::KeyValue {
+        rustmisc::KeyValue {
             key: "remote".to_string(),
             value: remote.to_string(),
         },
-        rustweb::KeyValue {
+        rustmisc::KeyValue {
             key: "body".to_string(),
             value: body.to_string(),
         },
@@ -532,11 +534,11 @@ fn log_response(
         let snippet = var.key.to_owned() + "=" + &var.value;
         str.push_str(&snippet);
     }
-    vec.push(rustweb::KeyValue {
+    vec.push(rustmisc::KeyValue {
         key: "headers".to_string(),
         value: str.to_string(),
     });
-    rustweb::log(logger, rustweb::Priority::Info, "Response details", &vec);
+    rustmisc::log(logger, rustmisc::Priority::Info, "Response details", &vec);
 }
 
 // Main entry point after a request arrived
@@ -546,7 +548,7 @@ async fn process_request(
     remote: SocketAddr,
 ) -> MyResult<Response<BoxBody>> {
     let unique = uuid::Uuid::new_v4();
-    let my_logger = rustweb::withValue(&ctx.logger, "uniqueid", &unique.to_string());
+    let my_logger = rustmisc::withValue(&ctx.logger, "uniqueid", &unique.to_string());
 
     // Convert  query part of URI into vars table
     let mut vars: Vec<rustweb::KeyValue> = vec![];
@@ -677,34 +679,34 @@ async fn process_request(
         header::CONNECTION,
         header::HeaderValue::from_str("close").unwrap(),
     );
-    if ctx.loglevel != rustweb::LogLevel::None {
+    if ctx.loglevel != rustmisc::LogLevel::None {
         let version = format!("{:?}", version);
-        rustweb::log(
+        rustmisc::log(
             &my_logger,
             rustweb::Priority::Notice,
             "Request",
             &vec![
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "remote".to_string(),
                     value: remote.to_string(),
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "method".to_string(),
                     value: method.to_string(),
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "urlpath".to_string(),
                     value: path.to_string(),
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "HTTPVersion".to_string(),
                     value: version,
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "status".to_string(),
                     value: response.status.to_string(),
                 },
-                rustweb::KeyValue {
+                rustmisc::KeyValue {
                     key: "respsize".to_string(),
                     value: len.to_string(),
                 },
@@ -738,13 +740,13 @@ async fn serveweb_async(
             match stream.peer_addr() {
                 Ok(addr) => {
                     address = addr;
-                    let combo = rustweb::comboaddress(&address.to_string());
-                    if !rustweb::matches(&ctx.acl, &combo) {
-                        rustweb::log(
+                    let combo = rustmisc::comboaddress(&address.to_string());
+                    if !rustmisc::matches(&ctx.acl, &combo) {
+                        rustmisc::log(
                             &ctx.logger,
                             rustweb::Priority::Debug,
                             "No ACL match",
-                            &vec![rustweb::KeyValue {
+                            &vec![rustmisc::KeyValue {
                                 key: "address".to_string(),
                                 value: address.to_string(),
                             }],
@@ -753,7 +755,7 @@ async fn serveweb_async(
                     }
                 }
                 Err(err) => {
-                    rustweb::error(
+                    rustmisc::error(
                         &ctx.logger,
                         rustweb::Priority::Error,
                         &err.to_string(),
@@ -769,7 +771,7 @@ async fn serveweb_async(
             let tls_stream = match tls_acceptor.accept(stream).await {
                 Ok(tls_stream) => tls_stream,
                 Err(err) => {
-                    rustweb::error(
+                    rustmisc::error(
                         &ctx.logger,
                         rustweb::Priority::Notice,
                         &err.to_string(),
@@ -780,7 +782,7 @@ async fn serveweb_async(
                 }
             };
             let io = TokioIo::new(tls_stream);
-            let my_logger = rustweb::withValue(&ctx.logger, "tls", "true");
+            let my_logger = rustmisc::withValue(&ctx.logger, "tls", "true");
             let fut = http1::Builder::new().serve_connection(
                 io,
                 service_fn(move |req| {
@@ -793,7 +795,7 @@ async fn serveweb_async(
             tokio::task::spawn(async move {
                 // Finally, we bind the incoming connection to our `process_request` service
                 if let Err(err) = fut.await {
-                    rustweb::error(
+                    rustmisc::error(
                         &my_logger,
                         rustweb::Priority::Notice,
                         &err.to_string(),
@@ -813,13 +815,13 @@ async fn serveweb_async(
             match stream.peer_addr() {
                 Ok(addr) => {
                     address = addr;
-                    let combo = rustweb::comboaddress(&address.to_string());
-                    if !rustweb::matches(&ctx.acl, &combo) {
-                        rustweb::log(
+                    let combo = rustmisc::comboaddress(&address.to_string());
+                    if !rustmisc::matches(&ctx.acl, &combo) {
+                        rustmisc::log(
                             &ctx.logger,
                             rustweb::Priority::Debug,
                             "No ACL match",
-                            &vec![rustweb::KeyValue {
+                            &vec![rustmisc::KeyValue {
                                 key: "address".to_string(),
                                 value: address.to_string(),
                             }],
@@ -828,9 +830,9 @@ async fn serveweb_async(
                     }
                 }
                 Err(err) => {
-                    rustweb::error(
+                    rustmisc::error(
                         &ctx.logger,
-                        rustweb::Priority::Error,
+                        rustmisc::Priority::Error,
                         &err.to_string(),
                         "Can't get peer address",
                         &vec![],
@@ -839,7 +841,7 @@ async fn serveweb_async(
                 }
             }
             let io = TokioIo::new(stream);
-            let my_logger = rustweb::withValue(&ctx.logger, "tls", "false");
+            let my_logger = rustmisc::withValue(&ctx.logger, "tls", "false");
             let fut = http1::Builder::new().serve_connection(
                 io,
                 service_fn(move |req| {
@@ -852,9 +854,9 @@ async fn serveweb_async(
             tokio::task::spawn(async move {
                 // Finally, we bind the incoming connection to our `process_request` service
                 if let Err(err) = fut.await {
-                    rustweb::error(
+                    rustmisc::error(
                         &my_logger,
-                        rustweb::Priority::Notice,
+                        rustmisc::Priority::Notice,
                         &err.to_string(),
                         "Error serving web connection",
                         &vec![],
@@ -870,9 +872,9 @@ pub fn serveweb(
     urls: &[String],
     password_ch: cxx::UniquePtr<rustweb::CredentialsHolder>,
     api_ch: cxx::UniquePtr<rustweb::CredentialsHolder>,
-    acl: cxx::UniquePtr<rustweb::NetmaskGroup>,
-    logger: cxx::SharedPtr<rustweb::Logger>,
-    loglevel: rustweb::LogLevel,
+    acl: cxx::UniquePtr<rustmisc::NetmaskGroup>,
+    logger: cxx::SharedPtr<rustmisc::Logger>,
+    loglevel: rustmisc::LogLevel,
 ) -> Result<(), std::io::Error> {
     // Context, atomically reference counted
     let ctx = Arc::new(Context {
@@ -895,7 +897,7 @@ pub fn serveweb(
     // waits (forever) for all of them to complete by joining them all.
     let mut set = JoinSet::new();
     for config in incoming {
-        rustweb::log(&ctx.logger, rustweb::Priority::Warning, "Config", &vec![]);
+        rustmisc::log(&ctx.logger, rustweb::Priority::Warning, "Config", &vec![]);
         for addr_str in &config.addresses {
             let addr = match SocketAddr::from_str(addr_str) {
                 Ok(val) => val,
@@ -913,21 +915,21 @@ pub fn serveweb(
                     let tls = crate::web::rustweb::IncomingTLS {
                         certificate: config.tls.certificate.clone(),
                         key: config.tls.key.clone(),
-                        password: config.tls.password.clone(),
+                        // password: config.tls.password.clone(), not supported (yet), ruttls does not handle it
                     };
                     if !tls.certificate.is_empty() {
                         tls_enabled = true;
                     }
-                    rustweb::log(
+                    rustmisc::log(
                         &ctx.logger,
                         rustweb::Priority::Info,
                         "web service listening",
                         &vec![
-                            rustweb::KeyValue {
+                            rustmisc::KeyValue {
                                 key: "address".to_string(),
                                 value: addr.to_string(),
                             },
-                            rustweb::KeyValue {
+                            rustmisc::KeyValue {
                                 key: "tls".to_string(),
                                 value: tls_enabled.to_string(),
                             },
@@ -937,12 +939,12 @@ pub fn serveweb(
                 }
                 Err(err) => {
                     let msg = format!("Unable to bind web socket: {}", err);
-                    rustweb::error(
+                    rustmisc::error(
                         &ctx.logger,
                         rustweb::Priority::Error,
                         &err.to_string(),
                         "Unable to bind to web socket",
-                        &vec![rustweb::KeyValue {
+                        &vec![rustmisc::KeyValue {
                             key: "address".to_string(),
                             value: addr.to_string(),
                         }],
@@ -958,9 +960,9 @@ pub fn serveweb(
             runtime.block_on(async {
                 while let Some(res) = set.join_next().await {
                     let msg = format!("{:?}", res);
-                    rustweb::error(
+                    rustmisc::error(
                         &ctx.logger,
-                        rustweb::Priority::Error,
+                        rustmisc::Priority::Error,
                         &msg,
                         "rustweb thread exited",
                         &vec![],
@@ -1004,24 +1006,31 @@ fn load_private_key(filename: &str) -> std::io::Result<pki_types::PrivateKeyDer<
 // impl below needed because the classes are used in the Context, which gets passed around.
 unsafe impl Send for rustweb::CredentialsHolder {}
 unsafe impl Sync for rustweb::CredentialsHolder {}
-unsafe impl Send for rustweb::NetmaskGroup {}
-unsafe impl Sync for rustweb::NetmaskGroup {}
-unsafe impl Send for rustweb::Logger {}
-unsafe impl Sync for rustweb::Logger {}
+unsafe impl Send for rustmisc::NetmaskGroup {}
+unsafe impl Sync for rustmisc::NetmaskGroup {}
+unsafe impl Send for rustmisc::Logger {}
+unsafe impl Sync for rustmisc::Logger {}
 
 #[cxx::bridge(namespace = "pdns::rust::web::rec")]
 mod rustweb {
     extern "C++" {
         type CredentialsHolder;
-        type NetmaskGroup;
-        type ComboAddress;
-        type Logger;
+        #[namespace = "pdns::rust::misc"]
+        type NetmaskGroup = crate::misc::rustmisc::NetmaskGroup;
+        //#[namespace = "pdns::rust::misc"]
+        //type ComboAddress = crate::misc::rustmisc::ComboAddress;
+        #[namespace = "pdns::rust::misc"]
+        type Priority = crate::misc::rustmisc::Priority;
+        #[namespace = "pdns::rust::misc"]
+        type LogLevel = crate::misc::rustmisc::LogLevel;
+        #[namespace = "pdns::rust::misc"]
+        type Logger = crate::misc::rustmisc::Logger;
     }
 
     pub struct IncomingTLS {
         certificate: String,
         key: String,
-        password: String,
+        // password: String, Not currently supported, as rusttls does not support that out of the box
     }
 
     struct IncomingWSConfig {
@@ -1063,26 +1072,12 @@ mod rustweb {
         headers: Vec<KeyValue>,
     }
 
-    enum Priority {
-        Absent = 0,
-        Alert = 1,
-        Critical = 2,
-        Error = 3,
-        Warning = 4,
-        Notice = 5,
-        Info = 6,
-        Debug = 7,
-    }
-    enum LogLevel {
-        None,
-        Normal,
-        Detailed,
-    }
     /*
      * Functions callable from Rust
      */
     unsafe extern "C++" {
         include!("bridge.hh");
+        fn matches(self: &CredentialsHolder, str: &CxxString) -> bool;
         fn apiDiscovery(request: &Request, response: &mut Response) -> Result<()>;
         fn apiDiscoveryV1(request: &Request, response: &mut Response) -> Result<()>;
         fn apiServer(request: &Request, response: &mut Response) -> Result<()>;
@@ -1110,18 +1105,5 @@ mod rustweb {
         fn jsonstat(request: &Request, response: &mut Response) -> Result<()>;
         fn prometheusMetrics(request: &Request, response: &mut Response) -> Result<()>;
         fn serveStuff(request: &Request, response: &mut Response) -> Result<()>;
-
-        fn matches(self: &CredentialsHolder, str: &CxxString) -> bool;
-        fn comboaddress(address: &str) -> UniquePtr<ComboAddress>;
-        fn matches(nmg: &UniquePtr<NetmaskGroup>, address: &UniquePtr<ComboAddress>) -> bool; // match is a keyword
-        fn withValue(logger: &SharedPtr<Logger>, key: &str, val: &str) -> SharedPtr<Logger>;
-        fn log(logger: &SharedPtr<Logger>, prio: Priority, msg: &str, values: &Vec<KeyValue>);
-        fn error(
-            logger: &SharedPtr<Logger>,
-            prio: Priority,
-            err: &str,
-            msg: &str,
-            values: &Vec<KeyValue>,
-        );
     }
 }
index dbd35484c56b53a348c3b556a2c40b90f73fcd98..b03a0c17309f104e73e7de1b6dc237206f870bf6 100644 (file)
@@ -46,6 +46,7 @@
 #include "settings/cxxsettings.hh" // IWYU pragma: keep, needed by included generated file
 #include "settings/rust/src/bridge.hh"
 #include "settings/rust/web.rs.h"
+#include "settings/rust/misc.rs.h"
 
 using json11::Json;
 
@@ -994,7 +995,7 @@ void serveRustWeb()
       for (const auto& address : listen.addresses) {
         tmp.addresses.emplace_back(address);
       }
-      tmp.tls = pdns::rust::web::rec::IncomingTLS{listen.tls.certificate, listen.tls.key, listen.tls.password};
+      tmp.tls = pdns::rust::web::rec::IncomingTLS{listen.tls.certificate, listen.tls.key};
       config.emplace_back(tmp);
     }
   }
@@ -1020,17 +1021,17 @@ void serveRustWeb()
   }
   NetmaskGroup acl;
   acl.toMasks(::arg()["webserver-allow-from"]);
-  auto aclPtr = std::make_unique<pdns::rust::web::rec::NetmaskGroup>(acl);
+  auto aclPtr = std::make_unique<pdns::rust::misc::NetmaskGroup>(acl);
 
   auto logPtr = g_slog->withName("webserver");
 
-  pdns::rust::web::rec::LogLevel loglevel = pdns::rust::web::rec::LogLevel::Normal;
+  pdns::rust::misc::LogLevel loglevel = pdns::rust::misc::LogLevel::Normal;
   auto configLevel = ::arg()["webserver-loglevel"];
   if (configLevel == "none") {
-    loglevel = pdns::rust::web::rec::LogLevel::Normal;
+    loglevel = pdns::rust::misc::LogLevel::Normal;
   }
   else if (configLevel == "detailed") {
-    loglevel = pdns::rust::web::rec::LogLevel::Detailed;
+    loglevel = pdns::rust::misc::LogLevel::Detailed;
   }
   pdns::rust::web::rec::serveweb(config, ::rust::Slice<const ::rust::String>{urls.data(), urls.size()}, std::move(password), std::move(apikey), std::move(aclPtr), std::move(logPtr), loglevel);
 }
index 882d29ba4fb3c2841208669305799166cde413fa..4be93d07263a600f396daf50b013c616208a1124 100644 (file)
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  */
 #pragma once
-#include <boost/utility.hpp>
-#include "namespaces.hh"
-#include "mplexer.hh"
+
 #include "webserver.hh"
 
 class HttpRequest;
 class HttpResponse;
+extern void serveRustWeb();
+
+#ifndef RUST_WS
+
+#include <boost/utility.hpp>
+#include "namespaces.hh"
+#include "mplexer.hh"
 
-#if 0
 class AsyncServer : public Server
 {
 public:
index e542bc54f9b1d74fbf59ada2c8865da8d2971305..767f986d3ec0d0d13e5f22fc1dc5259859fbfaa1 100644 (file)
@@ -21,6 +21,8 @@
  */
 #pragma once
 
+#include "config.h"
+
 #ifdef RECURSOR
 // Network facing/routing part of webserver is implemented in rust. We stil use a few classes from
 // yahttp, but do not link to it.