blob: 54c8376e051f8010d690349ee6a8e556594bb8db [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// Copyright 2012 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
Ben Murdochb8a8cc12014-11-26 15:28:44 +000028#include <include/v8.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000029
Ben Murdochb8a8cc12014-11-26 15:28:44 +000030#include <include/libplatform/libplatform.h>
31
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000032#include <stdlib.h>
33#include <string.h>
34
Steve Blocka7e24c12009-10-30 11:49:00 +000035#include <map>
Ben Murdochb8a8cc12014-11-26 15:28:44 +000036#include <string>
Steve Blocka7e24c12009-10-30 11:49:00 +000037
38using namespace std;
39using namespace v8;
40
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000041class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
42 public:
43 virtual void* Allocate(size_t length) {
44 void* data = AllocateUninitialized(length);
45 return data == NULL ? data : memset(data, 0, length);
46 }
47 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
48 virtual void Free(void* data, size_t) { free(data); }
49};
50
51
Steve Blocka7e24c12009-10-30 11:49:00 +000052// These interfaces represent an existing request processing interface.
53// The idea is to imagine a real application that uses these interfaces
54// and then add scripting capabilities that allow you to interact with
55// the objects through JavaScript.
56
57/**
58 * A simplified http request.
59 */
60class HttpRequest {
61 public:
62 virtual ~HttpRequest() { }
63 virtual const string& Path() = 0;
64 virtual const string& Referrer() = 0;
65 virtual const string& Host() = 0;
66 virtual const string& UserAgent() = 0;
67};
68
Ben Murdochb8a8cc12014-11-26 15:28:44 +000069
Steve Blocka7e24c12009-10-30 11:49:00 +000070/**
71 * The abstract superclass of http request processors.
72 */
73class HttpRequestProcessor {
74 public:
75 virtual ~HttpRequestProcessor() { }
76
77 // Initialize this processor. The map contains options that control
78 // how requests should be processed.
79 virtual bool Initialize(map<string, string>* options,
80 map<string, string>* output) = 0;
81
82 // Process a single request.
83 virtual bool Process(HttpRequest* req) = 0;
84
85 static void Log(const char* event);
86};
87
Ben Murdochb8a8cc12014-11-26 15:28:44 +000088
Steve Blocka7e24c12009-10-30 11:49:00 +000089/**
90 * An http request processor that is scriptable using JavaScript.
91 */
92class JsHttpRequestProcessor : public HttpRequestProcessor {
93 public:
Steve Blocka7e24c12009-10-30 11:49:00 +000094 // Creates a new processor that processes requests by invoking the
95 // Process function of the JavaScript script given as an argument.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000096 JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
97 : isolate_(isolate), script_(script) {}
Steve Blocka7e24c12009-10-30 11:49:00 +000098 virtual ~JsHttpRequestProcessor();
99
100 virtual bool Initialize(map<string, string>* opts,
101 map<string, string>* output);
102 virtual bool Process(HttpRequest* req);
103
104 private:
Steve Blocka7e24c12009-10-30 11:49:00 +0000105 // Execute the script associated with this processor and extract the
106 // Process function. Returns true if this succeeded, otherwise false.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000107 bool ExecuteScript(Local<String> script);
Steve Blocka7e24c12009-10-30 11:49:00 +0000108
109 // Wrap the options and output map in a JavaScript objects and
110 // install it in the global namespace as 'options' and 'output'.
111 bool InstallMaps(map<string, string>* opts, map<string, string>* output);
112
113 // Constructs the template that describes the JavaScript wrapper
114 // type for requests.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000115 static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
116 static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +0000117
118 // Callbacks that access the individual fields of request objects.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000119 static void GetPath(Local<String> name,
120 const PropertyCallbackInfo<Value>& info);
121 static void GetReferrer(Local<String> name,
122 const PropertyCallbackInfo<Value>& info);
123 static void GetHost(Local<String> name,
124 const PropertyCallbackInfo<Value>& info);
125 static void GetUserAgent(Local<String> name,
126 const PropertyCallbackInfo<Value>& info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000127
128 // Callbacks that access maps
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400129 static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
130 static void MapSet(Local<Name> name, Local<Value> value,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000131 const PropertyCallbackInfo<Value>& info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000132
133 // Utility methods for wrapping C++ objects as JavaScript objects,
134 // and going back again.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000135 Local<Object> WrapMap(map<string, string>* obj);
136 static map<string, string>* UnwrapMap(Local<Object> obj);
137 Local<Object> WrapRequest(HttpRequest* obj);
138 static HttpRequest* UnwrapRequest(Local<Object> obj);
Steve Blocka7e24c12009-10-30 11:49:00 +0000139
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000140 Isolate* GetIsolate() { return isolate_; }
141
142 Isolate* isolate_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000143 Local<String> script_;
144 Global<Context> context_;
145 Global<Function> process_;
146 static Global<ObjectTemplate> request_template_;
147 static Global<ObjectTemplate> map_template_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000148};
149
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000150
Steve Blocka7e24c12009-10-30 11:49:00 +0000151// -------------------------
152// --- P r o c e s s o r ---
153// -------------------------
154
155
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000156static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
157 if (args.Length() < 1) return;
158 HandleScope scope(args.GetIsolate());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000159 Local<Value> arg = args[0];
Steve Blocka7e24c12009-10-30 11:49:00 +0000160 String::Utf8Value value(arg);
161 HttpRequestProcessor::Log(*value);
Steve Blocka7e24c12009-10-30 11:49:00 +0000162}
163
164
165// Execute the script and fetch the Process method.
166bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
167 map<string, string>* output) {
168 // Create a handle scope to hold the temporary references.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000169 HandleScope handle_scope(GetIsolate());
Steve Blocka7e24c12009-10-30 11:49:00 +0000170
171 // Create a template for the global object where we set the
172 // built-in global functions.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000173 Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
174 global->Set(String::NewFromUtf8(GetIsolate(), "log", NewStringType::kNormal)
175 .ToLocalChecked(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000176 FunctionTemplate::New(GetIsolate(), LogCallback));
Steve Blocka7e24c12009-10-30 11:49:00 +0000177
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800178 // Each processor gets its own context so different processors don't
179 // affect each other. Context::New returns a persistent handle which
180 // is what we need for the reference to remain after we return from
181 // this method. That persistent handle has to be disposed in the
182 // destructor.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000183 v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000184 context_.Reset(GetIsolate(), context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000185
186 // Enter the new context so all the following operations take place
187 // within it.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000188 Context::Scope context_scope(context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000189
190 // Make the options mapping available within the context
191 if (!InstallMaps(opts, output))
192 return false;
193
194 // Compile and run the script
195 if (!ExecuteScript(script_))
196 return false;
197
198 // The script compiled and ran correctly. Now we fetch out the
199 // Process function from the global object.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000200 Local<String> process_name =
201 String::NewFromUtf8(GetIsolate(), "Process", NewStringType::kNormal)
202 .ToLocalChecked();
203 Local<Value> process_val;
Steve Blocka7e24c12009-10-30 11:49:00 +0000204 // If there is no Process function, or if it is not a function,
205 // bail out
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000206 if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
207 !process_val->IsFunction()) {
208 return false;
209 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000210
211 // It is a function; cast it to a Function
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000212 Local<Function> process_fun = Local<Function>::Cast(process_val);
Steve Blocka7e24c12009-10-30 11:49:00 +0000213
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000214 // Store the function in a Global handle, since we also want
Steve Blocka7e24c12009-10-30 11:49:00 +0000215 // that to remain after this call returns
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000216 process_.Reset(GetIsolate(), process_fun);
Steve Blocka7e24c12009-10-30 11:49:00 +0000217
218 // All done; all went well
219 return true;
220}
221
222
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000223bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000224 HandleScope handle_scope(GetIsolate());
Steve Blocka7e24c12009-10-30 11:49:00 +0000225
226 // We're just about to compile the script; set up an error handler to
227 // catch any exceptions the script might throw.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000228 TryCatch try_catch(GetIsolate());
229
230 Local<Context> context(GetIsolate()->GetCurrentContext());
Steve Blocka7e24c12009-10-30 11:49:00 +0000231
232 // Compile the script and check for errors.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000233 Local<Script> compiled_script;
234 if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000235 String::Utf8Value error(try_catch.Exception());
236 Log(*error);
237 // The script failed to compile; bail out.
238 return false;
239 }
240
241 // Run the script!
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000242 Local<Value> result;
243 if (!compiled_script->Run(context).ToLocal(&result)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000244 // The TryCatch above is still in effect and will have caught the error.
245 String::Utf8Value error(try_catch.Exception());
246 Log(*error);
247 // Running the script failed; bail out.
248 return false;
249 }
250 return true;
251}
252
253
254bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
255 map<string, string>* output) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000256 HandleScope handle_scope(GetIsolate());
Steve Blocka7e24c12009-10-30 11:49:00 +0000257
258 // Wrap the map object in a JavaScript wrapper
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000259 Local<Object> opts_obj = WrapMap(opts);
Steve Blocka7e24c12009-10-30 11:49:00 +0000260
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000261 v8::Local<v8::Context> context =
262 v8::Local<v8::Context>::New(GetIsolate(), context_);
263
Steve Blocka7e24c12009-10-30 11:49:00 +0000264 // Set the options object as a property on the global object.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000265 context->Global()
266 ->Set(context,
267 String::NewFromUtf8(GetIsolate(), "options", NewStringType::kNormal)
268 .ToLocalChecked(),
269 opts_obj)
270 .FromJust();
Steve Blocka7e24c12009-10-30 11:49:00 +0000271
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000272 Local<Object> output_obj = WrapMap(output);
273 context->Global()
274 ->Set(context,
275 String::NewFromUtf8(GetIsolate(), "output", NewStringType::kNormal)
276 .ToLocalChecked(),
277 output_obj)
278 .FromJust();
Steve Blocka7e24c12009-10-30 11:49:00 +0000279
280 return true;
281}
282
283
284bool JsHttpRequestProcessor::Process(HttpRequest* request) {
285 // Create a handle scope to keep the temporary object references.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000286 HandleScope handle_scope(GetIsolate());
287
288 v8::Local<v8::Context> context =
289 v8::Local<v8::Context>::New(GetIsolate(), context_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000290
291 // Enter this processor's context so all the remaining operations
292 // take place there
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000293 Context::Scope context_scope(context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000294
295 // Wrap the C++ request object in a JavaScript wrapper
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000296 Local<Object> request_obj = WrapRequest(request);
Steve Blocka7e24c12009-10-30 11:49:00 +0000297
298 // Set up an exception handler before calling the Process function
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000299 TryCatch try_catch(GetIsolate());
Steve Blocka7e24c12009-10-30 11:49:00 +0000300
301 // Invoke the process function, giving the global object as 'this'
302 // and one argument, the request.
303 const int argc = 1;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000304 Local<Value> argv[argc] = {request_obj};
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000305 v8::Local<v8::Function> process =
306 v8::Local<v8::Function>::New(GetIsolate(), process_);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000307 Local<Value> result;
308 if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000309 String::Utf8Value error(try_catch.Exception());
310 Log(*error);
311 return false;
312 } else {
313 return true;
314 }
315}
316
317
318JsHttpRequestProcessor::~JsHttpRequestProcessor() {
319 // Dispose the persistent handles. When noone else has any
320 // references to the objects stored in the handles they will be
321 // automatically reclaimed.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000322 context_.Reset();
323 process_.Reset();
Steve Blocka7e24c12009-10-30 11:49:00 +0000324}
325
326
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000327Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
328Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000329
330
331// -----------------------------------
332// --- A c c e s s i n g M a p s ---
333// -----------------------------------
334
335// Utility function that wraps a C++ http request object in a
336// JavaScript object.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000337Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
338 // Local scope for temporary handles.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000339 EscapableHandleScope handle_scope(GetIsolate());
Steve Blocka7e24c12009-10-30 11:49:00 +0000340
341 // Fetch the template for creating JavaScript map wrappers.
342 // It only has to be created once, which we do on demand.
Kristian Monsen25f61362010-05-21 11:50:48 +0100343 if (map_template_.IsEmpty()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000344 Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000345 map_template_.Reset(GetIsolate(), raw_template);
Steve Blocka7e24c12009-10-30 11:49:00 +0000346 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000347 Local<ObjectTemplate> templ =
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000348 Local<ObjectTemplate>::New(GetIsolate(), map_template_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000349
350 // Create an empty map wrapper.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000351 Local<Object> result =
352 templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
Steve Blocka7e24c12009-10-30 11:49:00 +0000353
354 // Wrap the raw C++ pointer in an External so it can be referenced
355 // from within JavaScript.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000356 Local<External> map_ptr = External::New(GetIsolate(), obj);
Steve Blocka7e24c12009-10-30 11:49:00 +0000357
358 // Store the map pointer in the JavaScript wrapper.
359 result->SetInternalField(0, map_ptr);
360
361 // Return the result through the current handle scope. Since each
362 // of these handles will go away when the handle scope is deleted
363 // we need to call Close to let one, the result, escape into the
364 // outer handle scope.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000365 return handle_scope.Escape(result);
Steve Blocka7e24c12009-10-30 11:49:00 +0000366}
367
368
369// Utility function that extracts the C++ map pointer from a wrapper
370// object.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000371map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
372 Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
Steve Blocka7e24c12009-10-30 11:49:00 +0000373 void* ptr = field->Value();
374 return static_cast<map<string, string>*>(ptr);
375}
376
377
378// Convert a JavaScript string to a std::string. To not bother too
379// much with string encodings we just use ascii.
380string ObjectToString(Local<Value> value) {
381 String::Utf8Value utf8_value(value);
382 return string(*utf8_value);
383}
384
385
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400386void JsHttpRequestProcessor::MapGet(Local<Name> name,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000387 const PropertyCallbackInfo<Value>& info) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400388 if (name->IsSymbol()) return;
389
Steve Blocka7e24c12009-10-30 11:49:00 +0000390 // Fetch the map wrapped by this object.
391 map<string, string>* obj = UnwrapMap(info.Holder());
392
393 // Convert the JavaScript string to a std::string.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400394 string key = ObjectToString(Local<String>::Cast(name));
Steve Blocka7e24c12009-10-30 11:49:00 +0000395
396 // Look up the value if it exists using the standard STL ideom.
397 map<string, string>::iterator iter = obj->find(key);
398
399 // If the key is not present return an empty handle as signal
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000400 if (iter == obj->end()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +0000401
402 // Otherwise fetch the value and wrap it in a JavaScript string
403 const string& value = (*iter).second;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000404 info.GetReturnValue().Set(
405 String::NewFromUtf8(info.GetIsolate(), value.c_str(),
406 NewStringType::kNormal,
407 static_cast<int>(value.length())).ToLocalChecked());
Steve Blocka7e24c12009-10-30 11:49:00 +0000408}
409
410
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400411void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000412 const PropertyCallbackInfo<Value>& info) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400413 if (name->IsSymbol()) return;
414
Steve Blocka7e24c12009-10-30 11:49:00 +0000415 // Fetch the map wrapped by this object.
416 map<string, string>* obj = UnwrapMap(info.Holder());
417
418 // Convert the key and value to std::strings.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400419 string key = ObjectToString(Local<String>::Cast(name));
Steve Blocka7e24c12009-10-30 11:49:00 +0000420 string value = ObjectToString(value_obj);
421
422 // Update the map.
423 (*obj)[key] = value;
424
425 // Return the value; any non-empty handle will work.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000426 info.GetReturnValue().Set(value_obj);
Steve Blocka7e24c12009-10-30 11:49:00 +0000427}
428
429
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000430Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000431 Isolate* isolate) {
432 EscapableHandleScope handle_scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +0000433
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000434 Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +0000435 result->SetInternalFieldCount(1);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400436 result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
Steve Blocka7e24c12009-10-30 11:49:00 +0000437
438 // Again, return the result through the current handle scope.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000439 return handle_scope.Escape(result);
Steve Blocka7e24c12009-10-30 11:49:00 +0000440}
441
442
443// -------------------------------------------
444// --- A c c e s s i n g R e q u e s t s ---
445// -------------------------------------------
446
447/**
448 * Utility function that wraps a C++ http request object in a
449 * JavaScript object.
450 */
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000451Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
452 // Local scope for temporary handles.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000453 EscapableHandleScope handle_scope(GetIsolate());
Steve Blocka7e24c12009-10-30 11:49:00 +0000454
455 // Fetch the template for creating JavaScript http request wrappers.
456 // It only has to be created once, which we do on demand.
457 if (request_template_.IsEmpty()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000458 Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000459 request_template_.Reset(GetIsolate(), raw_template);
Steve Blocka7e24c12009-10-30 11:49:00 +0000460 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000461 Local<ObjectTemplate> templ =
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000462 Local<ObjectTemplate>::New(GetIsolate(), request_template_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000463
464 // Create an empty http request wrapper.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000465 Local<Object> result =
466 templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
Steve Blocka7e24c12009-10-30 11:49:00 +0000467
468 // Wrap the raw C++ pointer in an External so it can be referenced
469 // from within JavaScript.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000470 Local<External> request_ptr = External::New(GetIsolate(), request);
Steve Blocka7e24c12009-10-30 11:49:00 +0000471
472 // Store the request pointer in the JavaScript wrapper.
473 result->SetInternalField(0, request_ptr);
474
475 // Return the result through the current handle scope. Since each
476 // of these handles will go away when the handle scope is deleted
477 // we need to call Close to let one, the result, escape into the
478 // outer handle scope.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000479 return handle_scope.Escape(result);
Steve Blocka7e24c12009-10-30 11:49:00 +0000480}
481
482
483/**
484 * Utility function that extracts the C++ http request object from a
485 * wrapper object.
486 */
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000487HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
488 Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
Steve Blocka7e24c12009-10-30 11:49:00 +0000489 void* ptr = field->Value();
490 return static_cast<HttpRequest*>(ptr);
491}
492
493
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000494void JsHttpRequestProcessor::GetPath(Local<String> name,
495 const PropertyCallbackInfo<Value>& info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000496 // Extract the C++ request object from the JavaScript wrapper.
497 HttpRequest* request = UnwrapRequest(info.Holder());
498
499 // Fetch the path.
500 const string& path = request->Path();
501
502 // Wrap the result in a JavaScript string and return it.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000503 info.GetReturnValue().Set(
504 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
505 NewStringType::kNormal,
506 static_cast<int>(path.length())).ToLocalChecked());
Steve Blocka7e24c12009-10-30 11:49:00 +0000507}
508
509
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000510void JsHttpRequestProcessor::GetReferrer(
511 Local<String> name,
512 const PropertyCallbackInfo<Value>& info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000513 HttpRequest* request = UnwrapRequest(info.Holder());
514 const string& path = request->Referrer();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000515 info.GetReturnValue().Set(
516 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
517 NewStringType::kNormal,
518 static_cast<int>(path.length())).ToLocalChecked());
Steve Blocka7e24c12009-10-30 11:49:00 +0000519}
520
521
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000522void JsHttpRequestProcessor::GetHost(Local<String> name,
523 const PropertyCallbackInfo<Value>& info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000524 HttpRequest* request = UnwrapRequest(info.Holder());
525 const string& path = request->Host();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000526 info.GetReturnValue().Set(
527 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
528 NewStringType::kNormal,
529 static_cast<int>(path.length())).ToLocalChecked());
Steve Blocka7e24c12009-10-30 11:49:00 +0000530}
531
532
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000533void JsHttpRequestProcessor::GetUserAgent(
534 Local<String> name,
535 const PropertyCallbackInfo<Value>& info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000536 HttpRequest* request = UnwrapRequest(info.Holder());
537 const string& path = request->UserAgent();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000538 info.GetReturnValue().Set(
539 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
540 NewStringType::kNormal,
541 static_cast<int>(path.length())).ToLocalChecked());
Steve Blocka7e24c12009-10-30 11:49:00 +0000542}
543
544
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000545Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000546 Isolate* isolate) {
547 EscapableHandleScope handle_scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +0000548
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000549 Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +0000550 result->SetInternalFieldCount(1);
551
552 // Add accessors for each of the fields of the request.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000553 result->SetAccessor(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000554 String::NewFromUtf8(isolate, "path", NewStringType::kInternalized)
555 .ToLocalChecked(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000556 GetPath);
557 result->SetAccessor(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000558 String::NewFromUtf8(isolate, "referrer", NewStringType::kInternalized)
559 .ToLocalChecked(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000560 GetReferrer);
561 result->SetAccessor(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000562 String::NewFromUtf8(isolate, "host", NewStringType::kInternalized)
563 .ToLocalChecked(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000564 GetHost);
565 result->SetAccessor(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000566 String::NewFromUtf8(isolate, "userAgent", NewStringType::kInternalized)
567 .ToLocalChecked(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000568 GetUserAgent);
Steve Blocka7e24c12009-10-30 11:49:00 +0000569
570 // Again, return the result through the current handle scope.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000571 return handle_scope.Escape(result);
Steve Blocka7e24c12009-10-30 11:49:00 +0000572}
573
574
575// --- Test ---
576
577
578void HttpRequestProcessor::Log(const char* event) {
579 printf("Logged: %s\n", event);
580}
581
582
583/**
584 * A simplified http request.
585 */
586class StringHttpRequest : public HttpRequest {
587 public:
588 StringHttpRequest(const string& path,
589 const string& referrer,
590 const string& host,
591 const string& user_agent);
592 virtual const string& Path() { return path_; }
593 virtual const string& Referrer() { return referrer_; }
594 virtual const string& Host() { return host_; }
595 virtual const string& UserAgent() { return user_agent_; }
596 private:
597 string path_;
598 string referrer_;
599 string host_;
600 string user_agent_;
601};
602
603
604StringHttpRequest::StringHttpRequest(const string& path,
605 const string& referrer,
606 const string& host,
607 const string& user_agent)
608 : path_(path),
609 referrer_(referrer),
610 host_(host),
611 user_agent_(user_agent) { }
612
613
614void ParseOptions(int argc,
615 char* argv[],
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000616 map<string, string>* options,
Steve Blocka7e24c12009-10-30 11:49:00 +0000617 string* file) {
618 for (int i = 1; i < argc; i++) {
619 string arg = argv[i];
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000620 size_t index = arg.find('=', 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000621 if (index == string::npos) {
622 *file = arg;
623 } else {
624 string key = arg.substr(0, index);
625 string value = arg.substr(index+1);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000626 (*options)[key] = value;
Steve Blocka7e24c12009-10-30 11:49:00 +0000627 }
628 }
629}
630
631
632// Reads a file into a v8 string.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000633MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000634 FILE* file = fopen(name.c_str(), "rb");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000635 if (file == NULL) return MaybeLocal<String>();
Steve Blocka7e24c12009-10-30 11:49:00 +0000636
637 fseek(file, 0, SEEK_END);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000638 size_t size = ftell(file);
Steve Blocka7e24c12009-10-30 11:49:00 +0000639 rewind(file);
640
641 char* chars = new char[size + 1];
642 chars[size] = '\0';
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000643 for (size_t i = 0; i < size;) {
644 i += fread(&chars[i], 1, size - i, file);
645 if (ferror(file)) {
646 fclose(file);
647 return MaybeLocal<String>();
648 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000649 }
650 fclose(file);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000651 MaybeLocal<String> result = String::NewFromUtf8(
652 isolate, chars, NewStringType::kNormal, static_cast<int>(size));
Steve Blocka7e24c12009-10-30 11:49:00 +0000653 delete[] chars;
654 return result;
655}
656
657
658const int kSampleSize = 6;
659StringHttpRequest kSampleRequests[kSampleSize] = {
660 StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"),
661 StringHttpRequest("/", "localhost", "google.net", "firefox"),
662 StringHttpRequest("/", "localhost", "google.org", "safari"),
663 StringHttpRequest("/", "localhost", "yahoo.com", "ie"),
664 StringHttpRequest("/", "localhost", "yahoo.com", "safari"),
665 StringHttpRequest("/", "localhost", "yahoo.com", "firefox")
666};
667
668
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000669bool ProcessEntries(v8::Platform* platform, HttpRequestProcessor* processor,
670 int count, StringHttpRequest* reqs) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000671 for (int i = 0; i < count; i++) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000672 bool result = processor->Process(&reqs[i]);
673 while (v8::platform::PumpMessageLoop(platform, Isolate::GetCurrent()))
674 continue;
675 if (!result) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000676 }
677 return true;
678}
679
680
681void PrintMap(map<string, string>* m) {
682 for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
683 pair<string, string> entry = *i;
684 printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
685 }
686}
687
688
689int main(int argc, char* argv[]) {
Ben Murdoch61f157c2016-09-16 13:49:30 +0100690 v8::V8::InitializeICUDefaultLocation(argv[0]);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000691 v8::V8::InitializeExternalStartupData(argv[0]);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000692 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
693 v8::V8::InitializePlatform(platform);
694 v8::V8::Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 map<string, string> options;
696 string file;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000697 ParseOptions(argc, argv, &options, &file);
Steve Blocka7e24c12009-10-30 11:49:00 +0000698 if (file.empty()) {
699 fprintf(stderr, "No script was specified.\n");
700 return 1;
701 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000702 ArrayBufferAllocator array_buffer_allocator;
703 Isolate::CreateParams create_params;
704 create_params.array_buffer_allocator = &array_buffer_allocator;
705 Isolate* isolate = Isolate::New(create_params);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000706 Isolate::Scope isolate_scope(isolate);
707 HandleScope scope(isolate);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000708 Local<String> source;
709 if (!ReadFile(isolate, file).ToLocal(&source)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000710 fprintf(stderr, "Error reading '%s'.\n", file.c_str());
711 return 1;
712 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000713 JsHttpRequestProcessor processor(isolate, source);
Steve Blocka7e24c12009-10-30 11:49:00 +0000714 map<string, string> output;
715 if (!processor.Initialize(&options, &output)) {
716 fprintf(stderr, "Error initializing processor.\n");
717 return 1;
718 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000719 if (!ProcessEntries(platform, &processor, kSampleSize, kSampleRequests))
Steve Blocka7e24c12009-10-30 11:49:00 +0000720 return 1;
721 PrintMap(&output);
722}