-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathprocess.rs
More file actions
379 lines (313 loc) · 10.5 KB
/
process.rs
File metadata and controls
379 lines (313 loc) · 10.5 KB
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
use std::collections::HashMap;
use std::convert::TryFrom;
#[allow(clippy::needless_pass_by_value)] // this function should follow the callback type
fn log_callback(
scope: &mut v8::PinScope,
args: v8::FunctionCallbackArguments,
mut _retval: v8::ReturnValue,
) {
let message = args
.get(0)
.to_string(scope)
.unwrap()
.to_rust_string_lossy(scope);
println!("Logged: {message}");
}
fn main() {
// Initialize V8.
let platform = v8::new_default_platform(0, false).make_shared();
v8::V8::initialize_platform(platform);
v8::V8::initialize();
// Parse options.
let (options, file) = parse_args();
if file.is_empty() {
panic!("no script was specified");
}
let mut isolate = v8::Isolate::new(v8::CreateParams::default());
v8::scope!(let scope, &mut isolate);
let source = std::fs::read_to_string(&file)
.unwrap_or_else(|err| panic!("failed to open {file}: {err}"));
let source = v8::String::new(scope, &source).unwrap();
let mut processor = JsHttpRequestProcessor::new(scope, source, options);
let requests = vec![
StringHttpRequest::new("/process.cc", "localhost", "google.com", "firefox"),
StringHttpRequest::new("/", "localhost", "google.net", "firefox"),
StringHttpRequest::new("/", "localhost", "google.org", "safari"),
StringHttpRequest::new("/", "localhost", "yahoo.com", "ie"),
StringHttpRequest::new("/", "localhost", "yahoo.com", "safari"),
StringHttpRequest::new("/", "localhost", "yahoo.com", "firefox"),
];
for req in requests {
processor.process(req);
}
processor.print_output();
}
fn parse_args() -> (HashMap<String, String>, String) {
use std::env;
let args: Vec<String> = env::args().collect();
let mut options = HashMap::new();
let mut file = String::new();
for arg in &args {
if let Some(pos) = arg.find('=') {
let (key, value) = arg.split_at(pos);
let value = &value[1..];
options.insert(key.into(), value.into());
} else {
file = arg.into();
}
}
(options, file)
}
/// A simplified HTTP request.
trait HttpRequest {
fn path(&self) -> &str;
fn referrer(&self) -> &str;
fn host(&self) -> &str;
fn user_agent(&self) -> &str;
}
/// A simplified HTTP request.
struct StringHttpRequest {
pub path: String,
pub referrer: String,
pub host: String,
pub user_agent: String,
}
impl StringHttpRequest {
/// Creates a `StringHttpRequest`.
pub fn new(
path: impl Into<String>,
referrer: impl Into<String>,
host: impl Into<String>,
user_agent: impl Into<String>,
) -> Self {
Self {
path: path.into(),
referrer: referrer.into(),
host: host.into(),
user_agent: user_agent.into(),
}
}
}
impl HttpRequest for StringHttpRequest {
fn path(&self) -> &str {
&self.path
}
fn referrer(&self) -> &str {
&self.referrer
}
fn host(&self) -> &str {
&self.host
}
fn user_agent(&self) -> &str {
&self.user_agent
}
}
/// An http request processor that is scriptable using JavaScript.
struct JsHttpRequestProcessor<'scope, 'obj, 'isolate> {
context: v8::Local<'obj, v8::Context>,
context_scope: v8::ContextScope<'scope, 'obj, v8::HandleScope<'isolate>>,
process_fn: Option<v8::Local<'obj, v8::Function>>,
request_template: v8::Global<v8::ObjectTemplate>,
_map_template: Option<v8::Global<v8::ObjectTemplate>>,
}
impl<'scope, 'obj, 'isolate> JsHttpRequestProcessor<'scope, 'obj, 'isolate> {
/// Creates a scriptable HTTP request processor.
pub fn new(
isolate_scope: &'scope mut v8::PinScope<'obj, 'isolate, ()>,
source: v8::Local<'obj, v8::String>,
options: HashMap<String, String>,
) -> Self {
let global = v8::ObjectTemplate::new(isolate_scope);
global.set(
v8::String::new(isolate_scope, "log").unwrap().into(),
v8::FunctionTemplate::new(isolate_scope, log_callback).into(),
);
let context = v8::Context::new(
isolate_scope,
v8::ContextOptions {
global_template: Some(global),
..Default::default()
},
);
let context_scope = v8::ContextScope::new(isolate_scope, context);
let request_template = v8::ObjectTemplate::new(&context_scope);
request_template.set_internal_field_count(1);
// make it global
let request_template = v8::Global::new(&context_scope, request_template);
let mut self_ = JsHttpRequestProcessor {
context,
context_scope,
process_fn: None,
request_template,
_map_template: None,
};
// loads options and output
let options = self_.wrap_map(options);
let options_str = v8::String::new(&self_.context_scope, "options").unwrap();
self_.context.global(&self_.context_scope).set(
&self_.context_scope,
options_str.into(),
options.into(),
);
let output = v8::Object::new(&self_.context_scope);
let output_str = v8::String::new(&self_.context_scope, "output").unwrap();
self_.context.global(&self_.context_scope).set(
&self_.context_scope,
output_str.into(),
output.into(),
);
// execute script
self_.execute_script(source);
let process_str = v8::String::new(&self_.context_scope, "Process").unwrap();
let process_fn = self_
.context
.global(&self_.context_scope)
.get(&self_.context_scope, process_str.into())
.expect("missing function Process");
let process_fn = v8::Local::<v8::Function>::try_from(process_fn)
.expect("function expected");
self_.process_fn = Some(process_fn);
self_
}
fn execute_script(&mut self, script: v8::Local<'scope, v8::String>) {
v8::scope!(let scope, &mut self.context_scope);
v8::tc_scope!(let try_catch, scope);
let script = v8::Script::compile(try_catch, script, None)
.expect("failed to compile script");
if script.run(try_catch).is_none() {
let exception = try_catch.exception().unwrap();
let exception_string = exception
.to_string(try_catch)
.unwrap()
.to_rust_string_lossy(try_catch);
panic!("{exception_string}");
}
}
/// Processes the given HTTP request.
pub fn process<R>(&mut self, request: R)
where
R: HttpRequest + 'static,
{
let request: Box<dyn HttpRequest> = Box::new(request);
let request = self.wrap_request(request);
v8::scope!(let scope, &mut self.context_scope);
v8::tc_scope!(let try_catch, scope);
let process_fn = self.process_fn.as_mut().unwrap();
let global = self.context.global(try_catch).into();
if process_fn
.call(try_catch, global, &[request.into()])
.is_none()
{
let exception = try_catch.exception().unwrap();
let exception_string = exception
.to_string(try_catch)
.unwrap()
.to_rust_string_lossy(try_catch);
panic!("{exception_string}");
}
}
/// Utility function that wraps a http request object in a JavaScript object.
fn wrap_request(
&mut self,
request: Box<dyn HttpRequest>,
) -> v8::Local<'scope, v8::Object> {
// TODO: fix memory leak
use std::ffi::c_void;
// Double-box to get C-sized reference of Box<dyn HttpRequest>
let request = Box::new(request);
// Local scope for temporary handles.
let scope = &mut self.context_scope;
let request_template = v8::Local::new(scope, &self.request_template);
let result = request_template.new_instance(scope).unwrap();
let external = v8::External::new(
scope,
Box::leak(request) as *mut Box<dyn HttpRequest> as *mut c_void,
);
result.set_internal_field(0, external.into());
let name = v8::String::new(scope, "path").unwrap().into();
result.set_accessor(scope, name, Self::request_prop_handler);
let name = v8::String::new(scope, "userAgent").unwrap().into();
result.set_accessor(scope, name, Self::request_prop_handler);
let name = v8::String::new(scope, "referrer").unwrap().into();
result.set_accessor(scope, name, Self::request_prop_handler);
let name = v8::String::new(scope, "host").unwrap().into();
result.set_accessor(scope, name, Self::request_prop_handler);
result
}
/// This handles the properties of `HttpRequest`
#[allow(clippy::needless_pass_by_value)] // this function should follow the callback type
fn request_prop_handler(
scope: &mut v8::PinScope,
key: v8::Local<v8::Name>,
args: v8::PropertyCallbackArguments,
mut rv: v8::ReturnValue,
) {
let holder = args.holder();
let external = Self::unwrap_request(scope, holder);
assert!(
!external.is_null(),
"the pointer to Box<dyn HttpRequest> should not be null"
);
let request = unsafe { &mut *external };
let key = key.to_string(scope).unwrap().to_rust_string_lossy(scope);
let value = match &*key {
"path" => request.path(),
"userAgent" => request.user_agent(),
"referrer" => request.referrer(),
"host" => request.host(),
_ => {
return;
}
};
rv.set(v8::String::new(scope, value).unwrap().into());
}
/// Utility function that extracts the http request object from a wrapper object.
fn unwrap_request(
scope: &v8::PinScope,
request: v8::Local<v8::Object>,
) -> *mut Box<dyn HttpRequest> {
let external = request
.get_internal_field(scope, 0)
.unwrap()
.cast::<v8::External>();
external.value() as *mut Box<dyn HttpRequest>
}
fn wrap_map(
&mut self,
options: HashMap<String, String>,
) -> v8::Local<'scope, v8::Object> {
// TODO: wrap map, not convert into Object
let scope = &self.context_scope;
let result = v8::Object::new(scope);
for (key, value) in options {
let key = v8::String::new(scope, &key).unwrap().into();
let value = v8::String::new(scope, &value).unwrap().into();
result.set(scope, key, value);
}
result
}
/// Prints the output.
pub fn print_output(&mut self) {
let scope: std::pin::Pin<&mut v8::ScopeStorage<v8::HandleScope<'_>>> =
std::pin::pin!(v8::HandleScope::new(&mut self.context_scope));
let scope = &scope.init();
let key = v8::String::new(scope, "output").unwrap();
let output = self
.context
.global(scope)
.get(scope, key.into())
.unwrap()
.to_object(scope)
.unwrap();
let props = output
.get_property_names(scope, v8::GetPropertyNamesArgsBuilder::new().build())
.unwrap();
for i in 0..props.length() {
let key = props.get_index(scope, i).unwrap();
let value = output.get(scope, key).unwrap();
let key = key.to_string(scope).unwrap().to_rust_string_lossy(scope);
let value = value.to_string(scope).unwrap().to_rust_string_lossy(scope);
println!("{key}: {value}");
}
}
}