1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // 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 
28 #include <include/v8.h>
29 
30 #include <include/libplatform/libplatform.h>
31 
32 #include <stdlib.h>
33 #include <string.h>
34 
35 #include <map>
36 #include <string>
37 
38 using std::map;
39 using std::pair;
40 using std::string;
41 
42 using v8::Context;
43 using v8::EscapableHandleScope;
44 using v8::External;
45 using v8::Function;
46 using v8::FunctionTemplate;
47 using v8::Global;
48 using v8::HandleScope;
49 using v8::Isolate;
50 using v8::Local;
51 using v8::MaybeLocal;
52 using v8::Name;
53 using v8::NamedPropertyHandlerConfiguration;
54 using v8::NewStringType;
55 using v8::Object;
56 using v8::ObjectTemplate;
57 using v8::PropertyCallbackInfo;
58 using v8::Script;
59 using v8::String;
60 using v8::TryCatch;
61 using v8::Value;
62 
63 // These interfaces represent an existing request processing interface.
64 // The idea is to imagine a real application that uses these interfaces
65 // and then add scripting capabilities that allow you to interact with
66 // the objects through JavaScript.
67 
68 /**
69  * A simplified http request.
70  */
71 class HttpRequest {
72  public:
~HttpRequest()73   virtual ~HttpRequest() { }
74   virtual const string& Path() = 0;
75   virtual const string& Referrer() = 0;
76   virtual const string& Host() = 0;
77   virtual const string& UserAgent() = 0;
78 };
79 
80 
81 /**
82  * The abstract superclass of http request processors.
83  */
84 class HttpRequestProcessor {
85  public:
~HttpRequestProcessor()86   virtual ~HttpRequestProcessor() { }
87 
88   // Initialize this processor.  The map contains options that control
89   // how requests should be processed.
90   virtual bool Initialize(map<string, string>* options,
91                           map<string, string>* output) = 0;
92 
93   // Process a single request.
94   virtual bool Process(HttpRequest* req) = 0;
95 
96   static void Log(const char* event);
97 };
98 
99 
100 /**
101  * An http request processor that is scriptable using JavaScript.
102  */
103 class JsHttpRequestProcessor : public HttpRequestProcessor {
104  public:
105   // Creates a new processor that processes requests by invoking the
106   // Process function of the JavaScript script given as an argument.
JsHttpRequestProcessor(Isolate * isolate,Local<String> script)107   JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
108       : isolate_(isolate), script_(script) {}
109   virtual ~JsHttpRequestProcessor();
110 
111   virtual bool Initialize(map<string, string>* opts,
112                           map<string, string>* output);
113   virtual bool Process(HttpRequest* req);
114 
115  private:
116   // Execute the script associated with this processor and extract the
117   // Process function.  Returns true if this succeeded, otherwise false.
118   bool ExecuteScript(Local<String> script);
119 
120   // Wrap the options and output map in a JavaScript objects and
121   // install it in the global namespace as 'options' and 'output'.
122   bool InstallMaps(map<string, string>* opts, map<string, string>* output);
123 
124   // Constructs the template that describes the JavaScript wrapper
125   // type for requests.
126   static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
127   static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
128 
129   // Callbacks that access the individual fields of request objects.
130   static void GetPath(Local<String> name,
131                       const PropertyCallbackInfo<Value>& info);
132   static void GetReferrer(Local<String> name,
133                           const PropertyCallbackInfo<Value>& info);
134   static void GetHost(Local<String> name,
135                       const PropertyCallbackInfo<Value>& info);
136   static void GetUserAgent(Local<String> name,
137                            const PropertyCallbackInfo<Value>& info);
138 
139   // Callbacks that access maps
140   static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
141   static void MapSet(Local<Name> name, Local<Value> value,
142                      const PropertyCallbackInfo<Value>& info);
143 
144   // Utility methods for wrapping C++ objects as JavaScript objects,
145   // and going back again.
146   Local<Object> WrapMap(map<string, string>* obj);
147   static map<string, string>* UnwrapMap(Local<Object> obj);
148   Local<Object> WrapRequest(HttpRequest* obj);
149   static HttpRequest* UnwrapRequest(Local<Object> obj);
150 
GetIsolate()151   Isolate* GetIsolate() { return isolate_; }
152 
153   Isolate* isolate_;
154   Local<String> script_;
155   Global<Context> context_;
156   Global<Function> process_;
157   static Global<ObjectTemplate> request_template_;
158   static Global<ObjectTemplate> map_template_;
159 };
160 
161 
162 // -------------------------
163 // --- P r o c e s s o r ---
164 // -------------------------
165 
166 
LogCallback(const v8::FunctionCallbackInfo<v8::Value> & args)167 static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
168   if (args.Length() < 1) return;
169   Isolate* isolate = args.GetIsolate();
170   HandleScope scope(isolate);
171   Local<Value> arg = args[0];
172   String::Utf8Value value(isolate, arg);
173   HttpRequestProcessor::Log(*value);
174 }
175 
176 
177 // Execute the script and fetch the Process method.
Initialize(map<string,string> * opts,map<string,string> * output)178 bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
179                                         map<string, string>* output) {
180   // Create a handle scope to hold the temporary references.
181   HandleScope handle_scope(GetIsolate());
182 
183   // Create a template for the global object where we set the
184   // built-in global functions.
185   Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
186   global->Set(GetIsolate(), "log",
187               FunctionTemplate::New(GetIsolate(), LogCallback));
188 
189   // Each processor gets its own context so different processors don't
190   // affect each other. Context::New returns a persistent handle which
191   // is what we need for the reference to remain after we return from
192   // this method. That persistent handle has to be disposed in the
193   // destructor.
194   v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
195   context_.Reset(GetIsolate(), context);
196 
197   // Enter the new context so all the following operations take place
198   // within it.
199   Context::Scope context_scope(context);
200 
201   // Make the options mapping available within the context
202   if (!InstallMaps(opts, output))
203     return false;
204 
205   // Compile and run the script
206   if (!ExecuteScript(script_))
207     return false;
208 
209   // The script compiled and ran correctly.  Now we fetch out the
210   // Process function from the global object.
211   Local<String> process_name =
212       String::NewFromUtf8Literal(GetIsolate(), "Process");
213   Local<Value> process_val;
214   // If there is no Process function, or if it is not a function,
215   // bail out
216   if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
217       !process_val->IsFunction()) {
218     return false;
219   }
220 
221   // It is a function; cast it to a Function
222   Local<Function> process_fun = Local<Function>::Cast(process_val);
223 
224   // Store the function in a Global handle, since we also want
225   // that to remain after this call returns
226   process_.Reset(GetIsolate(), process_fun);
227 
228   // All done; all went well
229   return true;
230 }
231 
232 
ExecuteScript(Local<String> script)233 bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
234   HandleScope handle_scope(GetIsolate());
235 
236   // We're just about to compile the script; set up an error handler to
237   // catch any exceptions the script might throw.
238   TryCatch try_catch(GetIsolate());
239 
240   Local<Context> context(GetIsolate()->GetCurrentContext());
241 
242   // Compile the script and check for errors.
243   Local<Script> compiled_script;
244   if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
245     String::Utf8Value error(GetIsolate(), try_catch.Exception());
246     Log(*error);
247     // The script failed to compile; bail out.
248     return false;
249   }
250 
251   // Run the script!
252   Local<Value> result;
253   if (!compiled_script->Run(context).ToLocal(&result)) {
254     // The TryCatch above is still in effect and will have caught the error.
255     String::Utf8Value error(GetIsolate(), try_catch.Exception());
256     Log(*error);
257     // Running the script failed; bail out.
258     return false;
259   }
260 
261   return true;
262 }
263 
264 
InstallMaps(map<string,string> * opts,map<string,string> * output)265 bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
266                                          map<string, string>* output) {
267   HandleScope handle_scope(GetIsolate());
268 
269   // Wrap the map object in a JavaScript wrapper
270   Local<Object> opts_obj = WrapMap(opts);
271 
272   v8::Local<v8::Context> context =
273       v8::Local<v8::Context>::New(GetIsolate(), context_);
274 
275   // Set the options object as a property on the global object.
276   context->Global()
277       ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "options"),
278             opts_obj)
279       .FromJust();
280 
281   Local<Object> output_obj = WrapMap(output);
282   context->Global()
283       ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "output"),
284             output_obj)
285       .FromJust();
286 
287   return true;
288 }
289 
290 
Process(HttpRequest * request)291 bool JsHttpRequestProcessor::Process(HttpRequest* request) {
292   // Create a handle scope to keep the temporary object references.
293   HandleScope handle_scope(GetIsolate());
294 
295   v8::Local<v8::Context> context =
296       v8::Local<v8::Context>::New(GetIsolate(), context_);
297 
298   // Enter this processor's context so all the remaining operations
299   // take place there
300   Context::Scope context_scope(context);
301 
302   // Wrap the C++ request object in a JavaScript wrapper
303   Local<Object> request_obj = WrapRequest(request);
304 
305   // Set up an exception handler before calling the Process function
306   TryCatch try_catch(GetIsolate());
307 
308   // Invoke the process function, giving the global object as 'this'
309   // and one argument, the request.
310   const int argc = 1;
311   Local<Value> argv[argc] = {request_obj};
312   v8::Local<v8::Function> process =
313       v8::Local<v8::Function>::New(GetIsolate(), process_);
314   Local<Value> result;
315   if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
316     String::Utf8Value error(GetIsolate(), try_catch.Exception());
317     Log(*error);
318     return false;
319   }
320   return true;
321 }
322 
323 
~JsHttpRequestProcessor()324 JsHttpRequestProcessor::~JsHttpRequestProcessor() {
325   // Dispose the persistent handles.  When no one else has any
326   // references to the objects stored in the handles they will be
327   // automatically reclaimed.
328   context_.Reset();
329   process_.Reset();
330 }
331 
332 
333 Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
334 Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
335 
336 
337 // -----------------------------------
338 // --- A c c e s s i n g   M a p s ---
339 // -----------------------------------
340 
341 // Utility function that wraps a C++ http request object in a
342 // JavaScript object.
WrapMap(map<string,string> * obj)343 Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
344   // Local scope for temporary handles.
345   EscapableHandleScope handle_scope(GetIsolate());
346 
347   // Fetch the template for creating JavaScript map wrappers.
348   // It only has to be created once, which we do on demand.
349   if (map_template_.IsEmpty()) {
350     Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
351     map_template_.Reset(GetIsolate(), raw_template);
352   }
353   Local<ObjectTemplate> templ =
354       Local<ObjectTemplate>::New(GetIsolate(), map_template_);
355 
356   // Create an empty map wrapper.
357   Local<Object> result =
358       templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
359 
360   // Wrap the raw C++ pointer in an External so it can be referenced
361   // from within JavaScript.
362   Local<External> map_ptr = External::New(GetIsolate(), obj);
363 
364   // Store the map pointer in the JavaScript wrapper.
365   result->SetInternalField(0, map_ptr);
366 
367   // Return the result through the current handle scope.  Since each
368   // of these handles will go away when the handle scope is deleted
369   // we need to call Close to let one, the result, escape into the
370   // outer handle scope.
371   return handle_scope.Escape(result);
372 }
373 
374 
375 // Utility function that extracts the C++ map pointer from a wrapper
376 // object.
UnwrapMap(Local<Object> obj)377 map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
378   Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
379   void* ptr = field->Value();
380   return static_cast<map<string, string>*>(ptr);
381 }
382 
383 
384 // Convert a JavaScript string to a std::string.  To not bother too
385 // much with string encodings we just use ascii.
ObjectToString(v8::Isolate * isolate,Local<Value> value)386 string ObjectToString(v8::Isolate* isolate, Local<Value> value) {
387   String::Utf8Value utf8_value(isolate, value);
388   return string(*utf8_value);
389 }
390 
391 
MapGet(Local<Name> name,const PropertyCallbackInfo<Value> & info)392 void JsHttpRequestProcessor::MapGet(Local<Name> name,
393                                     const PropertyCallbackInfo<Value>& info) {
394   if (name->IsSymbol()) return;
395 
396   // Fetch the map wrapped by this object.
397   map<string, string>* obj = UnwrapMap(info.Holder());
398 
399   // Convert the JavaScript string to a std::string.
400   string key = ObjectToString(info.GetIsolate(), Local<String>::Cast(name));
401 
402   // Look up the value if it exists using the standard STL ideom.
403   map<string, string>::iterator iter = obj->find(key);
404 
405   // If the key is not present return an empty handle as signal
406   if (iter == obj->end()) return;
407 
408   // Otherwise fetch the value and wrap it in a JavaScript string
409   const string& value = (*iter).second;
410   info.GetReturnValue().Set(
411       String::NewFromUtf8(info.GetIsolate(), value.c_str(),
412                           NewStringType::kNormal,
413                           static_cast<int>(value.length())).ToLocalChecked());
414 }
415 
416 
MapSet(Local<Name> name,Local<Value> value_obj,const PropertyCallbackInfo<Value> & info)417 void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
418                                     const PropertyCallbackInfo<Value>& info) {
419   if (name->IsSymbol()) return;
420 
421   // Fetch the map wrapped by this object.
422   map<string, string>* obj = UnwrapMap(info.Holder());
423 
424   // Convert the key and value to std::strings.
425   string key = ObjectToString(info.GetIsolate(), Local<String>::Cast(name));
426   string value = ObjectToString(info.GetIsolate(), value_obj);
427 
428   // Update the map.
429   (*obj)[key] = value;
430 
431   // Return the value; any non-empty handle will work.
432   info.GetReturnValue().Set(value_obj);
433 }
434 
435 
MakeMapTemplate(Isolate * isolate)436 Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
437     Isolate* isolate) {
438   EscapableHandleScope handle_scope(isolate);
439 
440   Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
441   result->SetInternalFieldCount(1);
442   result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
443 
444   // Again, return the result through the current handle scope.
445   return handle_scope.Escape(result);
446 }
447 
448 
449 // -------------------------------------------
450 // --- A c c e s s i n g   R e q u e s t s ---
451 // -------------------------------------------
452 
453 /**
454  * Utility function that wraps a C++ http request object in a
455  * JavaScript object.
456  */
WrapRequest(HttpRequest * request)457 Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
458   // Local scope for temporary handles.
459   EscapableHandleScope handle_scope(GetIsolate());
460 
461   // Fetch the template for creating JavaScript http request wrappers.
462   // It only has to be created once, which we do on demand.
463   if (request_template_.IsEmpty()) {
464     Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
465     request_template_.Reset(GetIsolate(), raw_template);
466   }
467   Local<ObjectTemplate> templ =
468       Local<ObjectTemplate>::New(GetIsolate(), request_template_);
469 
470   // Create an empty http request wrapper.
471   Local<Object> result =
472       templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
473 
474   // Wrap the raw C++ pointer in an External so it can be referenced
475   // from within JavaScript.
476   Local<External> request_ptr = External::New(GetIsolate(), request);
477 
478   // Store the request pointer in the JavaScript wrapper.
479   result->SetInternalField(0, request_ptr);
480 
481   // Return the result through the current handle scope.  Since each
482   // of these handles will go away when the handle scope is deleted
483   // we need to call Close to let one, the result, escape into the
484   // outer handle scope.
485   return handle_scope.Escape(result);
486 }
487 
488 
489 /**
490  * Utility function that extracts the C++ http request object from a
491  * wrapper object.
492  */
UnwrapRequest(Local<Object> obj)493 HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
494   Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
495   void* ptr = field->Value();
496   return static_cast<HttpRequest*>(ptr);
497 }
498 
499 
GetPath(Local<String> name,const PropertyCallbackInfo<Value> & info)500 void JsHttpRequestProcessor::GetPath(Local<String> name,
501                                      const PropertyCallbackInfo<Value>& info) {
502   // Extract the C++ request object from the JavaScript wrapper.
503   HttpRequest* request = UnwrapRequest(info.Holder());
504 
505   // Fetch the path.
506   const string& path = request->Path();
507 
508   // Wrap the result in a JavaScript string and return it.
509   info.GetReturnValue().Set(
510       String::NewFromUtf8(info.GetIsolate(), path.c_str(),
511                           NewStringType::kNormal,
512                           static_cast<int>(path.length())).ToLocalChecked());
513 }
514 
515 
GetReferrer(Local<String> name,const PropertyCallbackInfo<Value> & info)516 void JsHttpRequestProcessor::GetReferrer(
517     Local<String> name,
518     const PropertyCallbackInfo<Value>& info) {
519   HttpRequest* request = UnwrapRequest(info.Holder());
520   const string& path = request->Referrer();
521   info.GetReturnValue().Set(
522       String::NewFromUtf8(info.GetIsolate(), path.c_str(),
523                           NewStringType::kNormal,
524                           static_cast<int>(path.length())).ToLocalChecked());
525 }
526 
527 
GetHost(Local<String> name,const PropertyCallbackInfo<Value> & info)528 void JsHttpRequestProcessor::GetHost(Local<String> name,
529                                      const PropertyCallbackInfo<Value>& info) {
530   HttpRequest* request = UnwrapRequest(info.Holder());
531   const string& path = request->Host();
532   info.GetReturnValue().Set(
533       String::NewFromUtf8(info.GetIsolate(), path.c_str(),
534                           NewStringType::kNormal,
535                           static_cast<int>(path.length())).ToLocalChecked());
536 }
537 
538 
GetUserAgent(Local<String> name,const PropertyCallbackInfo<Value> & info)539 void JsHttpRequestProcessor::GetUserAgent(
540     Local<String> name,
541     const PropertyCallbackInfo<Value>& info) {
542   HttpRequest* request = UnwrapRequest(info.Holder());
543   const string& path = request->UserAgent();
544   info.GetReturnValue().Set(
545       String::NewFromUtf8(info.GetIsolate(), path.c_str(),
546                           NewStringType::kNormal,
547                           static_cast<int>(path.length())).ToLocalChecked());
548 }
549 
550 
MakeRequestTemplate(Isolate * isolate)551 Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
552     Isolate* isolate) {
553   EscapableHandleScope handle_scope(isolate);
554 
555   Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
556   result->SetInternalFieldCount(1);
557 
558   // Add accessors for each of the fields of the request.
559   result->SetAccessor(
560       String::NewFromUtf8Literal(isolate, "path", NewStringType::kInternalized),
561       GetPath);
562   result->SetAccessor(String::NewFromUtf8Literal(isolate, "referrer",
563                                                  NewStringType::kInternalized),
564                       GetReferrer);
565   result->SetAccessor(
566       String::NewFromUtf8Literal(isolate, "host", NewStringType::kInternalized),
567       GetHost);
568   result->SetAccessor(String::NewFromUtf8Literal(isolate, "userAgent",
569                                                  NewStringType::kInternalized),
570                       GetUserAgent);
571 
572   // Again, return the result through the current handle scope.
573   return handle_scope.Escape(result);
574 }
575 
576 
577 // --- Test ---
578 
579 
Log(const char * event)580 void HttpRequestProcessor::Log(const char* event) {
581   printf("Logged: %s\n", event);
582 }
583 
584 
585 /**
586  * A simplified http request.
587  */
588 class StringHttpRequest : public HttpRequest {
589  public:
590   StringHttpRequest(const string& path,
591                     const string& referrer,
592                     const string& host,
593                     const string& user_agent);
Path()594   virtual const string& Path() { return path_; }
Referrer()595   virtual const string& Referrer() { return referrer_; }
Host()596   virtual const string& Host() { return host_; }
UserAgent()597   virtual const string& UserAgent() { return user_agent_; }
598  private:
599   string path_;
600   string referrer_;
601   string host_;
602   string user_agent_;
603 };
604 
605 
StringHttpRequest(const string & path,const string & referrer,const string & host,const string & user_agent)606 StringHttpRequest::StringHttpRequest(const string& path,
607                                      const string& referrer,
608                                      const string& host,
609                                      const string& user_agent)
610     : path_(path),
611       referrer_(referrer),
612       host_(host),
613       user_agent_(user_agent) { }
614 
615 
ParseOptions(int argc,char * argv[],map<string,string> * options,string * file)616 void ParseOptions(int argc,
617                   char* argv[],
618                   map<string, string>* options,
619                   string* file) {
620   for (int i = 1; i < argc; i++) {
621     string arg = argv[i];
622     size_t index = arg.find('=', 0);
623     if (index == string::npos) {
624       *file = arg;
625     } else {
626       string key = arg.substr(0, index);
627       string value = arg.substr(index+1);
628       (*options)[key] = value;
629     }
630   }
631 }
632 
633 
634 // Reads a file into a v8 string.
ReadFile(Isolate * isolate,const string & name)635 MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
636   FILE* file = fopen(name.c_str(), "rb");
637   if (file == NULL) return MaybeLocal<String>();
638 
639   fseek(file, 0, SEEK_END);
640   size_t size = ftell(file);
641   rewind(file);
642 
643   std::unique_ptr<char> chars(new char[size + 1]);
644   chars.get()[size] = '\0';
645   for (size_t i = 0; i < size;) {
646     i += fread(&chars.get()[i], 1, size - i, file);
647     if (ferror(file)) {
648       fclose(file);
649       return MaybeLocal<String>();
650     }
651   }
652   fclose(file);
653   MaybeLocal<String> result = String::NewFromUtf8(
654       isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size));
655   return result;
656 }
657 
658 
659 const int kSampleSize = 6;
660 StringHttpRequest kSampleRequests[kSampleSize] = {
661   StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"),
662   StringHttpRequest("/", "localhost", "google.net", "firefox"),
663   StringHttpRequest("/", "localhost", "google.org", "safari"),
664   StringHttpRequest("/", "localhost", "yahoo.com", "ie"),
665   StringHttpRequest("/", "localhost", "yahoo.com", "safari"),
666   StringHttpRequest("/", "localhost", "yahoo.com", "firefox")
667 };
668 
ProcessEntries(v8::Isolate * isolate,v8::Platform * platform,HttpRequestProcessor * processor,int count,StringHttpRequest * reqs)669 bool ProcessEntries(v8::Isolate* isolate, v8::Platform* platform,
670                     HttpRequestProcessor* processor, int count,
671                     StringHttpRequest* reqs) {
672   for (int i = 0; i < count; i++) {
673     bool result = processor->Process(&reqs[i]);
674     while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
675     if (!result) return false;
676   }
677   return true;
678 }
679 
PrintMap(map<string,string> * m)680 void PrintMap(map<string, string>* m) {
681   for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
682     pair<string, string> entry = *i;
683     printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
684   }
685 }
686 
687 
main(int argc,char * argv[])688 int main(int argc, char* argv[]) {
689   v8::V8::InitializeICUDefaultLocation(argv[0]);
690   v8::V8::InitializeExternalStartupData(argv[0]);
691   std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
692   v8::V8::InitializePlatform(platform.get());
693   v8::V8::Initialize();
694   map<string, string> options;
695   string file;
696   ParseOptions(argc, argv, &options, &file);
697   if (file.empty()) {
698     fprintf(stderr, "No script was specified.\n");
699     return 1;
700   }
701   Isolate::CreateParams create_params;
702   create_params.array_buffer_allocator =
703       v8::ArrayBuffer::Allocator::NewDefaultAllocator();
704   Isolate* isolate = Isolate::New(create_params);
705   Isolate::Scope isolate_scope(isolate);
706   HandleScope scope(isolate);
707   Local<String> source;
708   if (!ReadFile(isolate, file).ToLocal(&source)) {
709     fprintf(stderr, "Error reading '%s'.\n", file.c_str());
710     return 1;
711   }
712   JsHttpRequestProcessor processor(isolate, source);
713   map<string, string> output;
714   if (!processor.Initialize(&options, &output)) {
715     fprintf(stderr, "Error initializing processor.\n");
716     return 1;
717   }
718   if (!ProcessEntries(isolate, platform.get(), &processor, kSampleSize,
719                       kSampleRequests)) {
720     return 1;
721   }
722   PrintMap(&output);
723 }
724