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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use hyper::{
header::{HeaderName, HeaderValue},
http::uri::PathAndQuery,
Method, StatusCode, Uri,
};
use crate::{proxy::query::Query, Filter, Result};
use super::{Attr, Config, Rule};
use std::{io::Write, str::FromStr};
impl<F> Filter for Config<F>
where
F: Filter + Sync,
{
async fn modify_request(&self, hostname: &str, req: &mut crate::Req<Vec<u8>>) -> Result<()> {
log::debug!("applying config request rules to {hostname}");
let Some(target) = &self.proxy.targets.iter().find(|t| t.hostname == hostname) else {
return Ok(());
};
for rule in &target.req {
log::trace!("applying request rule {rule:?}");
match rule {
Rule::Dump => {
let mut buf = Vec::<u8>::new();
let _ = writeln!(buf, "{}", req.uri().path());
for (key, value) in req.headers() {
if let Ok(v) = value.to_str() {
let _ = writeln!(buf, "{}: {}", key, v);
}
}
if let Ok(s) = std::str::from_utf8(&buf) {
log::info!("dump resp \n{s}")
} else {
log::error!("response is not text");
}
}
Rule::Intercept => self.intercept.modify_request(hostname, req).await?,
Rule::Set(attr, value) => match attr {
super::Attr::Method => {
let update = Method::from_str(value.as_str())?;
*req.method_mut() = update;
}
Attr::Status => {}
Attr::Path => {
let mut parts = req.uri().clone().into_parts();
let pq = if let Some(pq) = parts.path_and_query {
if let Some(query) = pq.query() {
PathAndQuery::from_str(&format!("{}?{}", value, query))?
} else {
PathAndQuery::from_str(value)?
}
} else {
PathAndQuery::from_str(value)?
};
parts.path_and_query = Some(pq);
*req.uri_mut() = Uri::from_parts(parts).unwrap();
}
Attr::Query(key) => {
let val = if value.is_empty() {
"".to_string()
} else {
format!("={value}")
};
let mut parts = req.uri().clone().into_parts();
let pq = if let Some(pq) = parts.path_and_query {
let mut query = Query::from(&pq);
query.push(key, Some(value));
query.to_path_and_query(pq.path())?
} else {
PathAndQuery::from_str(&format!("/?{key}{val}"))?
};
parts.path_and_query = Some(pq);
*req.uri_mut() = Uri::from_parts(parts).unwrap();
}
Attr::Header(key) => {
if let Ok(header) = HeaderValue::from_str(value) {
req.headers_mut()
.insert(HeaderName::from_bytes(key.as_bytes()).unwrap(), header);
}
}
Attr::Body => {
*req.body_mut() = value.as_bytes().to_owned();
}
},
Rule::Subst(attr, sub) => match attr {
Attr::Method => {
let method = req.method().as_str().to_string();
let res = match sub.subst(&self.interp, method).await {
Ok(res) => res,
Err(e) => {
log::error!("{}", e);
continue;
}
};
*req.method_mut() = match Method::from_str(&res) {
Ok(method) => method,
Err(e) => {
log::error!("{}", e);
continue;
}
}
}
Attr::Status => {}
Attr::Path => {
let path = req.uri().path().to_string();
let value = match sub.subst(&self.interp, path).await {
Ok(res) => res,
Err(e) => {
log::error!("{}", e);
continue;
}
};
let mut parts = req.uri().clone().into_parts();
let pq = if let Some(pq) = parts.path_and_query {
if let Some(query) = pq.query() {
PathAndQuery::from_str(&format!("{}?{}", value, query))?
} else {
PathAndQuery::from_str(&value)?
}
} else {
PathAndQuery::from_str(&value)?
};
parts.path_and_query = Some(pq);
*req.uri_mut() = Uri::from_parts(parts).unwrap();
}
Attr::Query(q) => {
if let Some(query) = req.uri().query() {
let query = Query::from(query);
let mut res = Query::default();
let mut set = false;
for (k, v) in query.iter() {
if k == q {
set = true;
let val = v.unwrap_or_default().to_string();
let val = match sub.subst(&self.interp, val).await {
Ok(res) => res,
Err(e) => {
log::error!("{}", e);
continue;
}
};
res.push(k, Some(&val));
} else {
res.push(k, v);
}
}
if set {
let mut parts = req.uri().clone().into_parts();
parts.path_and_query = match res.to_path_and_query(req.uri().path())
{
Ok(s) => Some(s),
Err(e) => {
log::error!("{e}");
continue;
}
};
*req.uri_mut() = Uri::from_parts(parts).unwrap();
}
}
}
Attr::Header(header) => {
for (name, value) in req.headers_mut() {
if name.as_str() == header {
let val = match std::str::from_utf8(value.as_bytes()) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
let res = match sub.subst(&self.interp, val.into()).await {
Ok(res) => res,
Err(e) => {
log::error!("{}", e);
continue;
}
};
*value = match HeaderValue::from_str(&res) {
Ok(v) => v,
Err(e) => {
log::error!("{}", e);
continue;
}
};
}
}
}
Attr::Body => {
let body = match std::str::from_utf8(req.body()) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
let res = match sub.subst(&self.interp, body.to_string()).await {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
*req.body_mut() = res.as_bytes().to_vec();
}
},
}
}
log::trace!("finished applying config request rules to {hostname}");
Ok(())
}
async fn modify_response(&self, hostname: &str, res: &mut crate::Res<Vec<u8>>) -> Result<()> {
log::debug!("applying response rules to {hostname}");
let Some(target) = self.proxy.targets.iter().find(|t| t.hostname == hostname) else {
return Ok(());
};
for rule in &target.resp {
log::trace!("applying response rule {rule:?}");
match rule {
Rule::Dump => {
let mut buf = Vec::<u8>::new();
let _ = writeln!(buf, "{}", res.status());
for (key, value) in res.headers() {
if let Ok(v) = value.to_str() {
let _ = writeln!(buf, "{}: {}", key, v);
}
}
let _ = writeln!(buf);
buf.extend_from_slice(res.body());
if let Ok(s) = std::str::from_utf8(&buf) {
log::info!("dump res\n{s}")
} else {
log::error!("response is not text");
}
}
Rule::Intercept => self.intercept.modify_response(hostname, res).await?,
Rule::Set(attr, value) => match attr {
Attr::Method => {}
Attr::Path => {}
Attr::Query(_) => {}
Attr::Status => {
let status = StatusCode::from_str(value).unwrap();
*res.status_mut() = status;
}
Attr::Header(key) => {
if let Ok(header) = HeaderValue::from_str(value) {
res.headers_mut()
.insert(HeaderName::from_bytes(key.as_bytes()).unwrap(), header);
}
}
Attr::Body => {
*res.body_mut() = value.as_bytes().to_owned();
}
},
Rule::Subst(attr, sub) => match attr {
Attr::Method => {}
Attr::Query(_) => {}
Attr::Path => {}
Attr::Status => {
let number = res.status().as_u16();
let new = match sub.sub_num(&self.interp, number as i64).await {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
let new = match u16::try_from(new) {
Ok(n) => n,
Err(e) => {
log::error!("{e}");
continue;
}
};
let new = match StatusCode::from_u16(new) {
Ok(n) => n,
Err(e) => {
log::error!("{e}");
continue;
}
};
*res.status_mut() = new;
}
Attr::Header(header) => {
for (name, value) in res.headers_mut() {
if name.as_str() == header {
let val = match std::str::from_utf8(value.as_bytes()) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
let new_val = match sub.subst(&self.interp, val.into()).await {
Ok(res) => res,
Err(e) => {
log::error!("{}", e);
continue;
}
};
*value = match HeaderValue::from_str(&new_val) {
Ok(v) => v,
Err(e) => {
log::error!("{}", e);
continue;
}
};
}
}
}
Attr::Body => {
let body = match std::str::from_utf8(res.body()) {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
let new = match sub.subst(&self.interp, body.to_string()).await {
Ok(s) => s,
Err(e) => {
log::error!("{}", e);
continue;
}
};
*res.body_mut() = new.as_bytes().to_vec();
}
},
}
}
Ok(())
}
}