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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use warp::Filter;
use usdpl_core::serdes::{Dumpable, Loadable};
use usdpl_core::{socket, RemoteCallResponse};
use super::{Callable, MutCallable, AsyncCallable, WrappedCallable};
static LAST_ID: AtomicU64 = AtomicU64::new(0);
const MAX_ID_DIFFERENCE: u64 = 5;
#[cfg(feature = "encrypt")]
const NONCE: [u8; socket::NONCE_SIZE] = [0u8; socket::NONCE_SIZE];
pub struct Instance {
calls: HashMap<String, WrappedCallable>,
port: u16,
#[cfg(feature = "encrypt")]
encryption_key: Vec<u8>,
}
impl Instance {
#[inline]
pub fn new(port_usdpl: u16) -> Self {
Instance {
calls: HashMap::new(),
port: port_usdpl,
#[cfg(feature = "encrypt")]
encryption_key: hex::decode(obfstr::obfstr!(env!("USDPL_ENCRYPTION_KEY"))).unwrap(),
}
}
pub fn register<S: std::convert::Into<String>, F: Callable + 'static>(
mut self,
name: S,
f: F,
) -> Self {
self.calls
.insert(name.into(), WrappedCallable::new_ref(f));
self
}
pub fn register_blocking<S: std::convert::Into<String>, F: MutCallable + 'static>(
mut self,
name: S,
f: F,
) -> Self {
self.calls
.insert(name.into(), WrappedCallable::new_locking(f));
self
}
pub fn register_async<S: std::convert::Into<String>, F: AsyncCallable + 'static>(
mut self,
name: S,
f: F,
) -> Self {
self.calls
.insert(name.into(), WrappedCallable::new_async(f));
self
}
#[cfg(feature = "blocking")]
pub fn run_blocking(&self) -> Result<(), ()> {
let result = self.serve_internal();
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(result)
}
pub async fn run(&self) -> Result<(), ()> {
self.serve_internal().await
}
#[async_recursion::async_recursion]
async fn handle_call(
packet: socket::Packet,
handlers: &HashMap<String, WrappedCallable>,
) -> socket::Packet {
match packet {
socket::Packet::Call(call) => {
log::debug!("Got USDPL call {} (`{}`, params: {})", call.id, call.function, call.parameters.len());
let last_id = LAST_ID.load(Ordering::SeqCst);
if call.id == 0 {
log::info!("Call ID is 0, assuming new connection (resetting last id)");
LAST_ID.store(0, Ordering::SeqCst);
} else if call.id > last_id && call.id - last_id < MAX_ID_DIFFERENCE {
LAST_ID.store(call.id, Ordering::SeqCst);
} else {
#[cfg(not(debug_assertions))]
{
log::error!("Got USDPL call with strange ID! got:{} last id:{} (rejecting packet)", call.id, last_id);
return socket::Packet::Invalid
}
#[cfg(debug_assertions)]
log::warn!("Got USDPL call with strange ID! got:{} last id:{} (in release mode this packet will be rejected)", call.id, last_id);
}
if let Some(target) = handlers.get(&call.function) {
let result = target.call(call.parameters).await;
socket::Packet::CallResponse(RemoteCallResponse {
id: call.id,
response: result,
})
} else {
socket::Packet::Invalid
}
}
socket::Packet::Many(packets) => {
let mut result = Vec::with_capacity(packets.len());
for packet in packets {
result.push(Self::handle_call(packet, handlers).await);
}
socket::Packet::Many(result)
}
_ => socket::Packet::Invalid,
}
}
#[cfg(not(feature = "encrypt"))]
async fn process_body((data, handlers): (bytes::Bytes, HashMap<String, WrappedCallable>)) -> impl warp::Reply {
let (packet, _) = match socket::Packet::load_base64(&data) {
Ok(x) => x,
Err(e) => {
return warp::reply::with_status(
warp::http::Response::builder()
.body(format!("Failed to load packet: {}", e)),
warp::http::StatusCode::from_u16(400).unwrap(),
)
}
};
let mut buffer = String::with_capacity(socket::PACKET_BUFFER_SIZE);
let response = Self::handle_call(packet, &handlers).await;
let _len = match response.dump_base64(&mut buffer) {
Ok(x) => x,
Err(e) => {
return warp::reply::with_status(
warp::http::Response::builder()
.body(format!("Failed to dump response packet: {}", e)),
warp::http::StatusCode::from_u16(500).unwrap(),
)
}
};
warp::reply::with_status(
warp::http::Response::builder().body(buffer),
warp::http::StatusCode::from_u16(200).unwrap(),
)
}
#[cfg(feature = "encrypt")]
async fn process_body((data, handlers, key): (bytes::Bytes, HashMap<String, WrappedCallable>, Vec<u8>)) -> impl warp::Reply {
let (packet, _) = match socket::Packet::load_encrypted(&data, &key, &NONCE) {
Ok(x) => x,
Err(_) => {
return warp::reply::with_status(
warp::http::Response::builder()
.body("Failed to load packet".to_string()),
warp::http::StatusCode::from_u16(400).unwrap(),
)
}
};
let mut buffer = Vec::with_capacity(socket::PACKET_BUFFER_SIZE);
let response = Self::handle_call(packet, &handlers).await;
let len = match response.dump_encrypted(&mut buffer, &key, &NONCE) {
Ok(x) => x,
Err(_) => {
return warp::reply::with_status(
warp::http::Response::builder()
.body("Failed to dump response packet".to_string()),
warp::http::StatusCode::from_u16(500).unwrap(),
)
}
};
buffer.truncate(len);
let string: String = String::from_utf8(buffer).unwrap().into();
warp::reply::with_status(
warp::http::Response::builder().body(string),
warp::http::StatusCode::from_u16(200).unwrap(),
)
}
async fn serve_internal(&self) -> Result<(), ()> {
let handlers = self.calls.clone();
#[cfg(not(feature = "encrypt"))]
let input_mapper = move |data: bytes::Bytes| { (data, handlers.clone()) };
#[cfg(feature = "encrypt")]
let key = self.encryption_key.clone();
#[cfg(feature = "encrypt")]
let input_mapper = move |data: bytes::Bytes| { (data, handlers.clone(), key.clone()) };
let calls = warp::post()
.and(warp::path!("usdpl" / "call"))
.and(warp::body::content_length_limit(
(socket::PACKET_BUFFER_SIZE * 2) as _,
))
.and(warp::body::bytes())
.map(input_mapper)
.then(Self::process_body)
.map(|reply| warp::reply::with_header(reply, "Access-Control-Allow-Origin", "*"));
#[cfg(debug_assertions)]
warp::serve(calls).run(([0, 0, 0, 0], self.port)).await;
#[cfg(not(debug_assertions))]
warp::serve(calls).run(([127, 0, 0, 1], self.port)).await;
Ok(())
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
}