process.cc 24.6 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

28
#include <stdlib.h>
29 30
#include <string.h>

31
#include <map>
32
#include <string>
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include "include/libplatform/libplatform.h"
#include "include/v8-array-buffer.h"
#include "include/v8-context.h"
#include "include/v8-exception.h"
#include "include/v8-external.h"
#include "include/v8-function.h"
#include "include/v8-initialization.h"
#include "include/v8-isolate.h"
#include "include/v8-local-handle.h"
#include "include/v8-object.h"
#include "include/v8-persistent-handle.h"
#include "include/v8-primitive.h"
#include "include/v8-script.h"
#include "include/v8-snapshot.h"
#include "include/v8-template.h"
#include "include/v8-value.h"

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
using std::map;
using std::pair;
using std::string;

using v8::Context;
using v8::EscapableHandleScope;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Global;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Name;
using v8::NamedPropertyHandlerConfiguration;
using v8::NewStringType;
using v8::Object;
using v8::ObjectTemplate;
using v8::PropertyCallbackInfo;
using v8::Script;
using v8::String;
using v8::TryCatch;
using v8::Value;
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

// These interfaces represent an existing request processing interface.
// The idea is to imagine a real application that uses these interfaces
// and then add scripting capabilities that allow you to interact with
// the objects through JavaScript.

/**
 * A simplified http request.
 */
class HttpRequest {
 public:
  virtual ~HttpRequest() { }
  virtual const string& Path() = 0;
  virtual const string& Referrer() = 0;
  virtual const string& Host() = 0;
  virtual const string& UserAgent() = 0;
};

93

94 95 96 97 98 99 100 101 102 103
/**
 * The abstract superclass of http request processors.
 */
class HttpRequestProcessor {
 public:
  virtual ~HttpRequestProcessor() { }

  // Initialize this processor.  The map contains options that control
  // how requests should be processed.
  virtual bool Initialize(map<string, string>* options,
104
                          map<string, string>* output) = 0;
105 106 107 108 109 110 111

  // Process a single request.
  virtual bool Process(HttpRequest* req) = 0;

  static void Log(const char* event);
};

112

113 114 115 116 117 118 119
/**
 * An http request processor that is scriptable using JavaScript.
 */
class JsHttpRequestProcessor : public HttpRequestProcessor {
 public:
  // Creates a new processor that processes requests by invoking the
  // Process function of the JavaScript script given as an argument.
120 121
  JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
      : isolate_(isolate), script_(script) {}
122 123 124
  virtual ~JsHttpRequestProcessor();

  virtual bool Initialize(map<string, string>* opts,
125
                          map<string, string>* output);
126 127 128
  virtual bool Process(HttpRequest* req);

 private:
129 130
  // Execute the script associated with this processor and extract the
  // Process function.  Returns true if this succeeded, otherwise false.
131
  bool ExecuteScript(Local<String> script);
132 133 134 135 136 137 138

  // Wrap the options and output map in a JavaScript objects and
  // install it in the global namespace as 'options' and 'output'.
  bool InstallMaps(map<string, string>* opts, map<string, string>* output);

  // Constructs the template that describes the JavaScript wrapper
  // type for requests.
139 140
  static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
  static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
141 142

  // Callbacks that access the individual fields of request objects.
143 144 145 146 147 148 149 150
  static void GetPath(Local<String> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetReferrer(Local<String> name,
                          const PropertyCallbackInfo<Value>& info);
  static void GetHost(Local<String> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetUserAgent(Local<String> name,
                           const PropertyCallbackInfo<Value>& info);
151 152

  // Callbacks that access maps
153 154
  static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
  static void MapSet(Local<Name> name, Local<Value> value,
155
                     const PropertyCallbackInfo<Value>& info);
156 157 158

  // Utility methods for wrapping C++ objects as JavaScript objects,
  // and going back again.
159 160 161 162
  Local<Object> WrapMap(map<string, string>* obj);
  static map<string, string>* UnwrapMap(Local<Object> obj);
  Local<Object> WrapRequest(HttpRequest* obj);
  static HttpRequest* UnwrapRequest(Local<Object> obj);
163

164
  Isolate* GetIsolate() { return isolate_; }
165

166
  Isolate* isolate_;
167 168 169 170 171
  Local<String> script_;
  Global<Context> context_;
  Global<Function> process_;
  static Global<ObjectTemplate> request_template_;
  static Global<ObjectTemplate> map_template_;
172 173
};

174

175 176 177 178 179
// -------------------------
// --- P r o c e s s o r ---
// -------------------------


180 181
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() < 1) return;
182 183
  Isolate* isolate = args.GetIsolate();
  HandleScope scope(isolate);
184
  Local<Value> arg = args[0];
185
  String::Utf8Value value(isolate, arg);
186 187 188 189 190 191
  HttpRequestProcessor::Log(*value);
}


// Execute the script and fetch the Process method.
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 197

  // Create a template for the global object where we set the
  // built-in global functions.
198
  Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
199
  global->Set(GetIsolate(), "log",
200
              FunctionTemplate::New(GetIsolate(), LogCallback));
201

202 203 204 205 206
  // Each processor gets its own context so different processors don't
  // affect each other. Context::New returns a persistent handle which
  // is what we need for the reference to remain after we return from
  // this method. That persistent handle has to be disposed in the
  // destructor.
207
  v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
208
  context_.Reset(GetIsolate(), context);
209 210 211

  // Enter the new context so all the following operations take place
  // within it.
212
  Context::Scope context_scope(context);
213 214 215 216 217 218 219 220 221 222 223

  // Make the options mapping available within the context
  if (!InstallMaps(opts, output))
    return false;

  // Compile and run the script
  if (!ExecuteScript(script_))
    return false;

  // The script compiled and ran correctly.  Now we fetch out the
  // Process function from the global object.
224
  Local<String> process_name =
225
      String::NewFromUtf8Literal(GetIsolate(), "Process");
226
  Local<Value> process_val;
227 228
  // If there is no Process function, or if it is not a function,
  // bail out
229 230 231 232
  if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
      !process_val->IsFunction()) {
    return false;
  }
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 242 243 244 245

  // All done; all went well
  return true;
}


246
bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
247
  HandleScope handle_scope(GetIsolate());
248 249 250

  // We're just about to compile the script; set up an error handler to
  // catch any exceptions the script might throw.
251
  TryCatch try_catch(GetIsolate());
252

253 254
  Local<Context> context(GetIsolate()->GetCurrentContext());

255
  // Compile the script and check for errors.
256 257
  Local<Script> compiled_script;
  if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
258
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
259 260 261 262 263 264
    Log(*error);
    // The script failed to compile; bail out.
    return false;
  }

  // Run the script!
265 266
  Local<Value> result;
  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 270 271 272
    Log(*error);
    // Running the script failed; bail out.
    return false;
  }
273

274 275 276 277 278
  return true;
}


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 286 287
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

288
  // Set the options object as a property on the global object.
289
  context->Global()
290
      ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "options"),
291 292 293 294 295
            opts_obj)
      .FromJust();

  Local<Object> output_obj = WrapMap(output);
  context->Global()
296
      ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "output"),
297 298
            output_obj)
      .FromJust();
299 300 301 302 303 304 305

  return true;
}


bool JsHttpRequestProcessor::Process(HttpRequest* request) {
  // Create a handle scope to keep the temporary object references.
306
  HandleScope handle_scope(GetIsolate());
307

308 309 310
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

311 312
  // Enter this processor's context so all the remaining operations
  // 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 322 323

  // Invoke the process function, giving the global object as 'this'
  // and one argument, the request.
  const int argc = 1;
324
  Local<Value> argv[argc] = {request_obj};
325 326
  v8::Local<v8::Function> process =
      v8::Local<v8::Function>::New(GetIsolate(), process_);
327 328
  Local<Value> result;
  if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
329
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
330 331 332
    Log(*error);
    return false;
  }
333
  return true;
334 335 336 337
}


JsHttpRequestProcessor::~JsHttpRequestProcessor() {
338
  // Dispose the persistent handles.  When no one else has any
339 340
  // references to the objects stored in the handles they will be
  // automatically reclaimed.
341 342
  context_.Reset();
  process_.Reset();
343 344 345
}


346 347
Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
348 349 350 351 352 353 354 355


// -----------------------------------
// --- A c c e s s i n g   M a p s ---
// -----------------------------------

// Utility function that wraps a C++ http request object in a
// JavaScript object.
356 357
Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
  // Local scope for temporary handles.
358
  EscapableHandleScope handle_scope(GetIsolate());
359 360 361

  // Fetch the template for creating JavaScript map wrappers.
  // 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 371
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
372 373 374

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
375
  Local<External> map_ptr = External::New(GetIsolate(), obj);
376 377 378 379 380 381 382 383

  // Store the map pointer in the JavaScript wrapper.
  result->SetInternalField(0, map_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
384
  return handle_scope.Escape(result);
385 386 387 388 389
}


// Utility function that extracts the C++ map pointer from a wrapper
// object.
390
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
391
  Local<External> field = obj->GetInternalField(0).As<External>();
392 393 394 395 396 397 398
  void* ptr = field->Value();
  return static_cast<map<string, string>*>(ptr);
}


// Convert a JavaScript string to a std::string.  To not bother too
// much with string encodings we just use ascii.
399 400
string ObjectToString(v8::Isolate* isolate, Local<Value> value) {
  String::Utf8Value utf8_value(isolate, value);
401
  return string(*utf8_value);
402 403 404
}


405
void JsHttpRequestProcessor::MapGet(Local<Name> name,
406
                                    const PropertyCallbackInfo<Value>& info) {
407 408
  if (name->IsSymbol()) return;

409 410 411 412
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the JavaScript string to a std::string.
413
  string key = ObjectToString(info.GetIsolate(), name.As<String>());
414 415 416 417 418

  // Look up the value if it exists using the standard STL ideom.
  map<string, string>::iterator iter = obj->find(key);

  // If the key is not present return an empty handle as signal
419
  if (iter == obj->end()) return;
420 421 422

  // Otherwise fetch the value and wrap it in a JavaScript string
  const string& value = (*iter).second;
423 424 425 426
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), value.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(value.length())).ToLocalChecked());
427 428 429
}


430
void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
431
                                    const PropertyCallbackInfo<Value>& info) {
432 433
  if (name->IsSymbol()) return;

434 435 436 437
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // 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 442 443 444

  // Update the map.
  (*obj)[key] = value;

  // Return the value; any non-empty handle will work.
445
  info.GetReturnValue().Set(value_obj);
446 447 448
}


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 464 465 466 467 468 469
}


// -------------------------------------------
// --- A c c e s s i n g   R e q u e s t s ---
// -------------------------------------------

/**
 * Utility function that wraps a C++ http request object in a
 * JavaScript object.
 */
470 471
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  // Local scope for temporary handles.
472
  EscapableHandleScope handle_scope(GetIsolate());
473 474 475 476

  // Fetch the template for creating JavaScript http request wrappers.
  // It only has to be created once, which we do on demand.
  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 485
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
486 487 488

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
489
  Local<External> request_ptr = External::New(GetIsolate(), request);
490 491 492 493 494 495 496 497

  // Store the request pointer in the JavaScript wrapper.
  result->SetInternalField(0, request_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
498
  return handle_scope.Escape(result);
499 500 501 502 503 504 505
}


/**
 * Utility function that extracts the C++ http request object from a
 * wrapper object.
 */
506
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
507
  Local<External> field = obj->GetInternalField(0).As<External>();
508 509 510 511 512
  void* ptr = field->Value();
  return static_cast<HttpRequest*>(ptr);
}


513 514
void JsHttpRequestProcessor::GetPath(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
515 516 517 518 519 520 521
  // Extract the C++ request object from the JavaScript wrapper.
  HttpRequest* request = UnwrapRequest(info.Holder());

  // Fetch the path.
  const string& path = request->Path();

  // Wrap the result in a JavaScript string and return it.
522 523 524 525
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
526 527 528
}


529 530 531
void JsHttpRequestProcessor::GetReferrer(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
532 533
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Referrer();
534 535 536 537
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
538 539 540
}


541 542
void JsHttpRequestProcessor::GetHost(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
543 544
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Host();
545 546 547 548
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
549 550 551
}


552 553 554
void JsHttpRequestProcessor::GetUserAgent(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
555 556
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->UserAgent();
557 558 559 560
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
561 562 563
}


564
Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
565
    Isolate* isolate) {
566
  EscapableHandleScope handle_scope(isolate);
567

568
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
569 570 571
  result->SetInternalFieldCount(1);

  // Add accessors for each of the fields of the request.
572
  result->SetAccessor(
573
      String::NewFromUtf8Literal(isolate, "path", NewStringType::kInternalized),
574
      GetPath);
575 576 577
  result->SetAccessor(String::NewFromUtf8Literal(isolate, "referrer",
                                                 NewStringType::kInternalized),
                      GetReferrer);
578
  result->SetAccessor(
579
      String::NewFromUtf8Literal(isolate, "host", NewStringType::kInternalized),
580
      GetHost);
581 582 583
  result->SetAccessor(String::NewFromUtf8Literal(isolate, "userAgent",
                                                 NewStringType::kInternalized),
                      GetUserAgent);
584 585

  // Again, return the result through the current handle scope.
586
  return handle_scope.Escape(result);
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
}


// --- Test ---


void HttpRequestProcessor::Log(const char* event) {
  printf("Logged: %s\n", event);
}


/**
 * A simplified http request.
 */
class StringHttpRequest : public HttpRequest {
 public:
603 604 605 606
  StringHttpRequest(const string& path,
                    const string& referrer,
                    const string& host,
                    const string& user_agent);
607 608 609 610 611 612 613 614 615 616 617 618 619
  virtual const string& Path() { return path_; }
  virtual const string& Referrer() { return referrer_; }
  virtual const string& Host() { return host_; }
  virtual const string& UserAgent() { return user_agent_; }
 private:
  string path_;
  string referrer_;
  string host_;
  string user_agent_;
};


StringHttpRequest::StringHttpRequest(const string& path,
620 621 622
                                     const string& referrer,
                                     const string& host,
                                     const string& user_agent)
623 624 625 626 627 628
    : path_(path),
      referrer_(referrer),
      host_(host),
      user_agent_(user_agent) { }


629 630
void ParseOptions(int argc,
                  char* argv[],
631
                  map<string, string>* options,
632
                  string* file) {
633 634
  for (int i = 1; i < argc; i++) {
    string arg = argv[i];
635
    size_t index = arg.find('=', 0);
636 637 638 639 640
    if (index == string::npos) {
      *file = arg;
    } else {
      string key = arg.substr(0, index);
      string value = arg.substr(index+1);
641
      (*options)[key] = value;
642 643 644 645 646 647
    }
  }
}


// Reads a file into a v8 string.
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 655
  rewind(file);

656 657
  std::unique_ptr<char> chars(new char[size + 1]);
  chars.get()[size] = '\0';
658
  for (size_t i = 0; i < size;) {
659
    i += fread(&chars.get()[i], 1, size - i, file);
660 661
    if (ferror(file)) {
      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 669 670 671 672 673 674 675 676 677 678 679 680 681
  return result;
}


const int kSampleSize = 6;
StringHttpRequest kSampleRequests[kSampleSize] = {
  StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"),
  StringHttpRequest("/", "localhost", "google.net", "firefox"),
  StringHttpRequest("/", "localhost", "google.org", "safari"),
  StringHttpRequest("/", "localhost", "yahoo.com", "ie"),
  StringHttpRequest("/", "localhost", "yahoo.com", "safari"),
  StringHttpRequest("/", "localhost", "yahoo.com", "firefox")
};

682 683 684
bool ProcessEntries(v8::Isolate* isolate, v8::Platform* platform,
                    HttpRequestProcessor* processor, int count,
                    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 691 692
  }
  return true;
}

693 694
void PrintMap(map<string, string>* m) {
  for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
695 696 697 698 699 700 701
    pair<string, string> entry = *i;
    printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
  }
}


int main(int argc, char* argv[]) {
702
  v8::V8::InitializeICUDefaultLocation(argv[0]);
vogelheim's avatar
vogelheim committed
703
  v8::V8::InitializeExternalStartupData(argv[0]);
704 705
  std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(platform.get());
706 707 708 709 710 711
#ifdef V8_SANDBOX
  if (!v8::V8::InitializeSandbox()) {
    fprintf(stderr, "Error initializing the V8 sandbox\n");
    return 1;
  }
#endif
712
  v8::V8::Initialize();
713 714
  map<string, string> options;
  string file;
715
  ParseOptions(argc, argv, &options, &file);
716 717 718 719
  if (file.empty()) {
    fprintf(stderr, "No script was specified.\n");
    return 1;
  }
720
  Isolate::CreateParams create_params;
721 722
  create_params.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
723
  Isolate* isolate = Isolate::New(create_params);
724
  Isolate::Scope isolate_scope(isolate);
725
  HandleScope scope(isolate);
726 727
  Local<String> source;
  if (!ReadFile(isolate, file).ToLocal(&source)) {
728 729 730
    fprintf(stderr, "Error reading '%s'.\n", file.c_str());
    return 1;
  }
731
  JsHttpRequestProcessor processor(isolate, source);
732 733 734 735 736
  map<string, string> output;
  if (!processor.Initialize(&options, &output)) {
    fprintf(stderr, "Error initializing processor.\n");
    return 1;
  }
737 738
  if (!ProcessEntries(isolate, platform.get(), &processor, kSampleSize,
                      kSampleRequests)) {
739
    return 1;
740
  }
741
  PrintMap(&output);
742
}