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