1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#![allow(unused)]

use async_trait::async_trait;
use dyn_clone::DynClone;
use std::fmt::Debug;


use crate::dns_socket::DnsSocket;

#[derive(thiserror::Error, Debug)]
pub enum CustomHandlerError {
    #[error(transparent)]
    IO(#[from] crate::dns_socket::RequestError),

    #[error("Query is not processed by handler. Fallback to ICANN.")]
    Unhandled,
}

/**
 * Trait to implement to make AnyDns use a custom handler.
 * Important: Handler must be clonable so it can be used by multiple threads.
 */
#[async_trait]
pub trait CustomHandler: DynClone + Send + Sync {
    async fn lookup(
        &mut self,
        query: &Vec<u8>,
        socket: DnsSocket,
    ) -> Result<Vec<u8>, CustomHandlerError>;
}

/**
 * Clonable handler holder
 */
pub struct HandlerHolder {
    pub func: Box<dyn CustomHandler>,
}

impl Clone for HandlerHolder {
    fn clone(&self) -> Self {
        Self {
            func: dyn_clone::clone_box(&*self.func),
        }
    }
}

impl Debug for HandlerHolder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HandlerHolder")
            .field("func", &"HandlerHolder")
            .finish()
    }
}

impl HandlerHolder {
    /**
     * Bootstrap a holder from a struct that implements the CustomHandler.
     */
    pub fn new(f: impl CustomHandler + 'static) -> Self {
        HandlerHolder { func: Box::new(f) }
    }

    pub async fn call(
        &mut self,
        query: &Vec<u8>,
        socket: DnsSocket,
    ) -> Result<Vec<u8>, CustomHandlerError> {
        self.func.lookup(query, socket).await
    }
}

#[derive(Clone)]
pub struct EmptyHandler {}

impl EmptyHandler {
    pub fn new() -> Self {
        EmptyHandler {}
    }
}

#[async_trait]
impl CustomHandler for EmptyHandler {
    async fn lookup(
        &mut self,
        _query: &Vec<u8>,
        _socket: DnsSocket,
    ) -> Result<Vec<u8>, CustomHandlerError> {
        Err(CustomHandlerError::Unhandled)
    }
}

#[cfg(test)]
mod tests {
    use crate::dns_socket::DnsSocket;
    use async_trait::async_trait;
    use std::net::SocketAddr;

    use super::{CustomHandler, CustomHandlerError, HandlerHolder};

    struct ClonableStruct {
        value: String,
    }

    impl Clone for ClonableStruct {
        fn clone(&self) -> Self {
            Self {
                value: format!("{} cloned", self.value.clone()),
            }
        }
    }

    #[derive(Clone)]
    pub struct TestHandler {
        value: ClonableStruct,
    }

    impl TestHandler {
        pub fn new(value: &str) -> Self {
            TestHandler {
                value: ClonableStruct {
                    value: value.to_string(),
                },
            }
        }
    }
    #[async_trait]
    impl CustomHandler for TestHandler {
        async fn lookup(
            &mut self,
            _query: &Vec<u8>,
            _socket: DnsSocket,
        ) -> Result<Vec<u8>, CustomHandlerError> {
            println!("value {}", self.value.value);
            Err(CustomHandlerError::Unhandled)
        }
    }

    #[tokio::test]
    async fn run_processor() {
        let test1 = TestHandler::new("test1");
        let holder1 = HandlerHolder::new(test1);
        let mut cloned = holder1.clone();
        let icann_fallback: SocketAddr = "8.8.8.8:53".parse().unwrap();

        let socket = DnsSocket::new(
            "0.0.0.0:18293".parse().unwrap(),
            icann_fallback,
            holder1.clone(),
            true
        )
        .await
        .unwrap();
        let result = cloned.call(&vec![], socket).await;
        assert!(result.is_err());
    }
}