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
#![forbid(unsafe_code)]
#![warn(
missing_docs,
rust_2018_idioms,
missing_debug_implementations,
rustdoc::broken_intra_doc_links
)]
use std::{
io, marker,
net::{SocketAddr, UdpSocket},
};
pub use dominion_parser::body::name::*;
pub use dominion_parser::body::*;
pub use dominion_parser::header::*;
pub use dominion_parser::*;
pub trait ServerService {
fn run<'a>(&self, client: SocketAddr, question: &'a DnsPacket<'a>) -> Option<DnsPacket<'a>>;
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct Builder;
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct Runner;
#[derive(Debug)]
pub struct Server<S> {
threads: usize,
socket: Option<UdpSocket>,
typestate: marker::PhantomData<S>,
}
impl<S> Server<S> {
pub fn new() -> Server<Builder> {
Server::<Builder>::default()
}
}
impl Default for Server<Builder> {
fn default() -> Self {
Server {
threads: 1,
socket: None,
typestate: marker::PhantomData,
}
}
}
impl Server<Builder> {
pub fn threads(mut self, n: usize) -> Self {
self.threads = n;
self
}
pub fn bind(self, addr: SocketAddr) -> Result<Server<Runner>, io::Error> {
Ok(Server {
threads: self.threads,
socket: Some(UdpSocket::bind(addr)?),
typestate: marker::PhantomData::<Runner>,
})
}
}
impl Server<Runner> {
pub fn serve<T>(self, srv: T)
where
T: ServerService + Sync,
{
std::thread::scope(|s| {
for _ in 0..self.threads {
s.spawn(|| {
self.serve_sth(&srv)
.expect("Unexpected error when sending or recieving from the socket")
});
}
})
}
fn serve_sth(&self, srv: &impl ServerService) -> Result<(), std::io::Error> {
let mut buff = [0; 512];
loop {
let (n, src) = self
.socket
.as_ref()
.expect("Runners can only be created with a active socket")
.recv_from(&mut buff)?;
let packet = match DnsPacket::try_from(&buff[..n]) {
Ok(packet) => packet,
Err(_) => continue,
};
if let Some(res) = srv.run(src, &packet) {
let serialized = Vec::<u8>::from(&res);
self.socket
.as_ref()
.expect("Runners can only be created with a active socket")
.send_to(&serialized[..], src)?;
};
}
}
}