-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.rs
511 lines (473 loc) · 16.1 KB
/
http.rs
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::convert::From;
use std::str::FromStr;
use std::mem;
use lazy_static::lazy_static;
use gio::{
IOStream, IOStreamExt, InputStreamExtManual, OutputStreamExtManual, SocketClient,
SocketClientExt, SocketConnection, TlsCertificateFlags,
};
use glib::source::PRIORITY_DEFAULT;
use glib::Cast;
use relm::{connect_async, Relm, Update, UpdateNew};
use serde_yaml;
use regex::Regex;
use url::Url;
use super::super::errors::{RustamanError, RustamanResult};
use super::super::models::Environment;
use super::handlebars::compile_template;
const READ_SIZE: usize = 1024;
lazy_static! {
pub static ref RE_EXTRACT_AUTHORITY_FROM_DIRECTIVE: Regex =
Regex::new(r"#![\s]*Authority:[\s]*(?P<host>.+):(?P<port>[0-9]+)").unwrap();
pub static ref RE_EXTRACT_INSECURE_FLAG: Regex =
Regex::new(r"#![\s]*Allow Insecure Certificate").unwrap();
pub static ref RE_SPLIT_HTTP_FIRST_LINE: Regex = Regex::new("[ ]+").unwrap();
pub static ref RE_EXTRACT_CAPTURE: Regex =
Regex::new(r"#![\s]*Capture:\s*(?P<capture>.+)").unwrap();
pub static ref RE_SPLIT_END_CAPTURE: Regex =
Regex::new(r"#![\s]*EndCapture").unwrap();
}
fn parse_response(response: &str) -> Option<serde_yaml::Value> {
let mut is_json = false;
let mut has_content = true;
let mut text = String::new();
let mut lines = response.lines();
loop {
let line = lines.next();
match line {
Some(unwrapped) => {
if unwrapped.is_empty() {
break;
}
if unwrapped.starts_with("Content-Type: application/json") {
is_json = true;
}
}
None => has_content = false,
}
}
if has_content {
loop {
let line = lines.next();
match line {
Some(unwrapped) => {
text.push_str(unwrapped);
text.push('\n');
}
None => break
}
}
};
if is_json && has_content {
let resp: serde_yaml::Value = serde_json::from_str(text.as_str()).unwrap();
Some(resp)
} else {
None
}
}
fn extract_authority_from_directive(line: &str) -> Option<(String, u16)> {
let resp = RE_EXTRACT_AUTHORITY_FROM_DIRECTIVE
.captures(line)
.and_then(|cap| {
let host = cap
.name("host")
.map(|host| host.as_str().trim_start_matches("[").trim_end_matches("]"));
let port = cap
.name("port")
.map(|port| FromStr::from_str(port.as_str()).unwrap());
Some((host.unwrap().to_string(), port.unwrap()))
});
resp
}
fn extract_capture_name(line: &str) -> Option<String> {
let resp = RE_EXTRACT_CAPTURE
.captures(line)
.and_then(|cap| {
let cap = cap.name("capture");
if let Some(capture) = cap {
Some(capture.as_str().to_string())
}
else {
None
}
});
resp
}
fn extract_insecure_flag(line: &str) -> bool {
return RE_EXTRACT_INSECURE_FLAG.is_match(line);
}
#[derive(Debug, PartialEq, Clone)]
pub enum Scheme {
HTTP,
HTTPS,
Err(String), // until TryFrom is stable
}
impl<'a> From<&'a str> for Scheme {
fn from(value: &str) -> Self {
match value {
"http" => Scheme::HTTP,
"https" => Scheme::HTTPS,
_ => Scheme::Err(value.to_owned()),
}
}
}
#[derive(Debug, Clone)]
pub struct HttpRequest {
scheme: Scheme,
host: String,
port: u16,
http_frame: String,
tls_flags: TlsCertificateFlags,
capture: Option<String>,
}
impl HttpRequest {
pub fn http_frame(&self) -> &str {
self.http_frame.as_str()
}
pub fn authority(&self) -> (&str, u16) {
(self.host.as_str(), self.port)
}
/// Obfusface the http_frame
pub fn obfuscate(&self, env: &Environment) -> HttpRequest {
let mut req = self.clone();
let s = env.obfuscated_string();
let _: Vec<_> = s
.iter()
.map(|ref x| {
let obf = format!("{}...", &x[0..3]);
req.http_frame = req.http_frame.replace(x.as_str(), obf.as_str())
}).collect();
req
}
}
pub fn parse_request(request: &str) -> RustamanResult<HttpRequest> {
info!("Parsing request {}", request.len());
let mut lines = request.lines();
let mut line = lines.next();
let mut authority: Option<(String, u16)> = None;
let mut tls_flags = TlsCertificateFlags::all();
let mut capture = None;
loop {
if line.is_none() {
break;
}
let unwrapped = line.unwrap();
if !unwrapped.is_empty() && !unwrapped.starts_with('#') {
break;
}
if let Some(auth) = extract_authority_from_directive(unwrapped) {
debug!("Authority found from the request comment: {:?}", auth);
authority = Some(auth);
} else if let Some(cap) = extract_capture_name(unwrapped) {
capture = Some(cap);
} else if extract_insecure_flag(unwrapped) {
tls_flags = TlsCertificateFlags::empty();
} else {
debug!("Ignoring comment {}", unwrapped);
}
line = lines.next();
}
if line.is_none() {
error!("No request found");
return Err(RustamanError::RequestParsingError(
"No request found".to_owned(),
));
}
info!("Parsing First line {:?}", line);
let verb_url_version: Vec<&str> = RE_SPLIT_HTTP_FIRST_LINE.split(line.unwrap()).collect();
let (verb, url, version) = match verb_url_version.len() {
2 => (verb_url_version[0], verb_url_version[1], "HTTP/1.1"),
3 => (
verb_url_version[0],
verb_url_version[1],
verb_url_version[2],
),
_ => {
error!("Parse error on line: {}", line.unwrap());
return Err(RustamanError::RequestParsingError(
format!("Parse error on line: {}", line.unwrap()).to_owned(),
));
}
};
let url = url.parse::<Url>()?;
if authority.is_none() {
let host = url.host_str().ok_or(RustamanError::RequestParsingError(
"Host not found in HTTP Request".to_string(),
))?;
let port = url
.port_or_known_default()
.ok_or(RustamanError::RequestParsingError(
"Unknown http port to query".to_string(),
))?;
authority = Some((host.to_string(), port));
}
let mut query = url.path().to_string();
if let Some(qr) = url.query() {
query.push_str("?");
query.push_str(qr);
}
if let Some(frag) = url.fragment() {
query.push_str("#");
query.push_str(frag);
}
let scheme = Scheme::from(url.scheme());
if let Scheme::Err(error) = scheme {
info!("Scheme parsed from {:?}", url);
return Err(RustamanError::RequestParsingError(error));
}
let mut http_frame = format!("{} {} {}\r\n", verb, query, version);
loop {
let line = lines.next();
match line {
Some(unwrapped) => {
if unwrapped.is_empty() {
break;
}
http_frame.push_str(unwrapped);
http_frame.push_str("\r\n");
}
None => break,
}
}
if let Some(domain) = url.domain() {
http_frame.push_str("Host: ");
http_frame.push_str(domain);
http_frame.push_str("\r\n");
}
let mut body = String::new();
loop {
let line = lines.next();
match line {
Some(unwrapped) => {
body.push_str(unwrapped);
body.push_str("\r\n");
}
None => break,
}
}
if body.len() > 0 {
let length = format!("{}", body.len());
http_frame.push_str("Content-Length: ");
http_frame.push_str(length.as_str());
http_frame.push_str("\r\n");
}
if http_frame.find("\nUser-Agent:").is_none() {
http_frame.push_str("User-Agent: Rustaman\r\n");
}
http_frame.push_str("Connection: close\r\n");
http_frame.push_str("\r\n");
if body.len() > 0 {
http_frame.push_str(body.as_str());
}
let authority = authority.unwrap();
let (host, port) = (authority.0, authority.1);
info!("Http request built");
Ok(HttpRequest {
scheme,
host,
port,
http_frame,
tls_flags,
capture
})
}
#[derive(Debug, Clone)]
pub struct HttpRequests {
requests: Vec<String>
}
fn parse_template(template: &str) -> HttpRequests {
let requests: Vec<String> = RE_SPLIT_END_CAPTURE
.split(template)
.map(|request| { request.to_string() })
.collect();
debug!("{:?}", requests);
HttpRequests{requests}
}
pub struct HttpModel {
request: HttpRequests,
current_request: Option<HttpRequest>,
current_request_idx: usize,
error: Option<RustamanError>,
context: serde_yaml::Value,
response: Vec<u8>,
relm: Relm<Http>,
stream: Option<IOStream>,
}
#[derive(Msg)]
pub enum Msg {
StartConsuming,
StartConsumingHttpRequest,
Connecting(HttpRequest),
ConnectionAquired(SocketConnection, HttpRequest),
DisplayError(RustamanError),
Read((Vec<u8>, usize)),
CaptureReadDone(String),
ReadDone(String),
Writing(HttpRequest),
Wrote((Vec<u8>, usize)),
}
unsafe impl Send for Msg {}
pub struct Http {
model: HttpModel,
}
impl Update for Http {
type Model = HttpModel;
type ModelParam = (String, serde_yaml::Value);
type Msg = Msg;
fn model(relm: &Relm<Self>, params: Self::ModelParam) -> HttpModel {
let (http_request, context) = params;
// Fix errors
let request = parse_template(http_request.as_str());
let response = Vec::new();
HttpModel {
request,
context,
response,
relm: relm.clone(),
error: None,
stream: None,
current_request: None,
current_request_idx: 0,
}
}
fn subscriptions(&mut self, _relm: &Relm<Self>) {}
fn update(&mut self, message: Msg) {
match message {
Msg::StartConsuming => {
let error = mem::replace(&mut self.model.error, None);
if let Some(err) = error {
self.model
.relm
.stream()
.emit(Msg::DisplayError(err));
}
else {
self.model
.relm
.stream()
.emit(Msg::StartConsumingHttpRequest);
}
}
Msg::StartConsumingHttpRequest => {
if self.model.current_request_idx < self.model.request.requests.len() {
info!("StartConsumingHttpRequest: {} / {}",
self.model.current_request_idx + 1, self.model.request.requests.len());
let req = self.model.request.requests.get(self.model.current_request_idx).unwrap();
let http_request =
compile_template(req.as_str(), &self.model.context).unwrap_or("".to_owned());
info!("{}", http_request);
let req = parse_request(http_request.as_str());
if let Err(err) = req {
self.model
.relm
.stream()
.emit(Msg::DisplayError(err));
}
else {
// start consuming without error here
let req = req.unwrap();
self.model.current_request = Some(req.clone());
self.model
.relm
.stream()
.emit(Msg::Connecting(req));
}
}
}
Msg::Connecting(req) => {
info!("Connecting: {:?}", self.model.request.requests);
let client = SocketClient::new();
if req.scheme == Scheme::HTTPS {
client.set_tls(true);
client.set_tls_validation_flags(req.tls_flags);
}
let host = req.host.clone();
connect_async!(
client,
connect_to_host_async(host.as_str(), req.port),
self.model.relm,
|conn| Msg::ConnectionAquired(conn, req),
|err: gdk::Error| Msg::DisplayError(RustamanError::from(err.clone()))
);
},
Msg::ConnectionAquired(connection, req) => {
info!("Connecting to {:?}", connection);
let stream: IOStream = connection.upcast();
let writer = stream.get_output_stream().expect("output");
self.model.stream = Some(stream);
let buffer = req.http_frame.as_str().to_string().into_bytes();
self.model.relm.stream().emit(Msg::Writing(req.clone()));
connect_async!(
writer,
write_async(buffer, PRIORITY_DEFAULT),
self.model.relm,
|msg| Msg::Wrote(msg)
);
}
// To be listened by the user.
Msg::Read((mut buffer, size)) => {
if size == 0 {
let buffer = String::from_utf8(self.model.response.clone()).unwrap();
self.model.current_request_idx += 1;
if self.model.current_request_idx == self.model.request.requests.len() {
self.model.relm.stream().emit(Msg::ReadDone(buffer));
}
else {
self.model.relm.stream().emit(Msg::CaptureReadDone(buffer));
}
} else {
if let Some(ref stream) = self.model.stream {
let reader = stream.get_input_stream().expect("input");
connect_async!(
reader,
read_async(vec![0; READ_SIZE], PRIORITY_DEFAULT),
self.model.relm,
Msg::Read
);
}
}
buffer.truncate(size);
self.model.response.extend(&buffer);
}
// To be listened by the user.
Msg::CaptureReadDone(response) | Msg::ReadDone(response) => {
let req = mem::replace(&mut self.model.current_request, None);
let req = req.unwrap();
if let Some(capture) = req.capture {
let resp = parse_response(response.as_str());
if let Some(r) = resp {
match &mut self.model.context {
serde_yaml::Value::Mapping(mapping) => {
mapping.insert(serde_yaml::Value::String(capture.to_string()), r);
}
_ => {}
}
}
}
self.model.response.clear();
self.model
.relm
.stream()
.emit(Msg::StartConsumingHttpRequest);
},
Msg::Writing(_) => (),
Msg::Wrote(_) => {
if let Some(ref stream) = self.model.stream {
let reader = stream.get_input_stream().expect("input");
connect_async!(
reader,
read_async(vec![0; READ_SIZE], PRIORITY_DEFAULT),
self.model.relm,
Msg::Read
);
}
}
_ => {}
}
}
}
impl UpdateNew for Http {
fn new(_relm: &Relm<Self>, model: HttpModel) -> Self {
Http { model }
}
}