#include <stdlib.h>
#include <string.h>
 
#include <map>
#include <string>
 
 
using std::map;
using std::pair;
using std::string;
 
 
 
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;
};
 
 
class HttpRequestProcessor {
 public:
  virtual ~HttpRequestProcessor() { }
 
  
  
  virtual bool Initialize(map<string, string>* options,
                          map<string, string>* output) = 0;
 
  
  virtual bool Process(HttpRequest* req) = 0;
 
  static void Log(const char* event);
};
 
 
class JsHttpRequestProcessor : public HttpRequestProcessor {
 public:
  
  
  JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
      : isolate_(isolate), script_(script) {}
  virtual ~JsHttpRequestProcessor();
 
  virtual bool Initialize(map<string, string>* opts,
                          map<string, string>* output);
  virtual bool Process(HttpRequest* req);
 
 private:
  
  
  bool ExecuteScript(Local<String> script);
 
  
  
  bool InstallMaps(map<string, string>* opts, map<string, string>* output);
 
  
  
  static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
  static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
 
  
  static void GetPath(Local<Name> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetReferrer(Local<Name> name,
                          const PropertyCallbackInfo<Value>& info);
  static void GetHost(Local<Name> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetUserAgent(Local<Name> name,
                           const PropertyCallbackInfo<Value>& info);
 
  
                                const PropertyCallbackInfo<Value>& info);
                                const PropertyCallbackInfo<void>& info);
 
  
  
  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);
 
  Isolate* GetIsolate() { return isolate_; }
 
  Isolate* isolate_;
  Local<String> script_;
  Global<Context> context_;
  Global<Function> process_;
  static Global<ObjectTemplate> request_template_;
  static Global<ObjectTemplate> map_template_;
};
 
 
 
  if (info.
Length() < 1) 
return;
 
  HandleScope scope(isolate);
  Local<Value> arg = info[0];
  String::Utf8Value value(isolate, arg);
  HttpRequestProcessor::Log(*value);
}
 
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
                                        map<string, string>* output) {
  
  HandleScope handle_scope(GetIsolate());
 
  
  
  Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
  global->Set(GetIsolate(), "log",
              FunctionTemplate::New(GetIsolate(), LogCallback));
 
  
  
  
  
  
  context_.Reset(GetIsolate(), context);
 
  
  
  Context::Scope context_scope(context);
 
  
  if (!InstallMaps(opts, output))
    return false;
 
  
  if (!ExecuteScript(script_))
    return false;
 
  
  
  Local<String> process_name =
      String::NewFromUtf8Literal(GetIsolate(), "Process");
  Local<Value> process_val;
  
  
  if (!context->
Global()->Get(context, process_name).ToLocal(&process_val) ||
 
      !process_val->IsFunction()) {
    return false;
  }
 
  
  Local<Function> process_fun = process_val.As<Function>();
 
  
  
  process_.Reset(GetIsolate(), process_fun);
 
  
  return true;
}
 
 
bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
  HandleScope handle_scope(GetIsolate());
 
  
  
  TryCatch try_catch(GetIsolate());
 
  Local<Context> context(GetIsolate()->GetCurrentContext());
 
  
  Local<Script> compiled_script;
  if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
    Log(*error);
    
    return false;
  }
 
  
  Local<Value> result;
  if (!compiled_script->Run(context).ToLocal(&result)) {
    
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
    Log(*error);
    
    return false;
  }
 
  return true;
}
 
 
bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
                                         map<string, string>* output) {
  HandleScope handle_scope(GetIsolate());
 
  
  Local<Object> opts_obj = WrapMap(opts);
 
 
  
      ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "options"),
            opts_obj)
      .FromJust();
 
  Local<Object> output_obj = WrapMap(output);
      ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "output"),
            output_obj)
      .FromJust();
 
  return true;
}
 
 
bool JsHttpRequestProcessor::Process(HttpRequest* request) {
  
  HandleScope handle_scope(GetIsolate());
 
 
  
  
  Context::Scope context_scope(context);
 
  
  Local<Object> request_obj = WrapRequest(request);
 
  
  TryCatch try_catch(GetIsolate());
 
  
  
  const int argc = 1;
  Local<Value> argv[argc] = {request_obj};
  Local<Value> result;
  if (!process->Call(context, context->
Global(), argc, argv).ToLocal(&result)) {
 
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
    Log(*error);
    return false;
  }
  return true;
}
 
 
JsHttpRequestProcessor::~JsHttpRequestProcessor() {
  
  
  
  context_.Reset();
  process_.Reset();
}
 
Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
 
 
namespace {
}  
 
Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
  
  EscapableHandleScope handle_scope(GetIsolate());
 
  
  
  if (map_template_.IsEmpty()) {
    Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
    map_template_.Reset(GetIsolate(), raw_template);
  }
  Local<ObjectTemplate> templ =
      Local<ObjectTemplate>::New(GetIsolate(), map_template_);
 
  
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
 
  
  
  Local<External> map_ptr = External::New(GetIsolate(), obj, kMapTag);
 
  
  result->SetInternalField(0, map_ptr);
 
  
  
  
  
  return handle_scope.Escape(result);
}
 
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
  Local<External> field = obj->GetInternalField(0).As<Value>().As<External>();
  void* ptr = field->Value(kMapTag);
  return static_cast<map<string, string>*>(ptr);
}
 
string ObjectToString(
v8::Isolate* isolate, Local<Value> value) {
 
  String::Utf8Value utf8_value(isolate, value);
  return string(*utf8_value);
}
 
    Local<Name> name, const PropertyCallbackInfo<Value>& info) {
 
  
  map<string, string>* obj = UnwrapMap(info.HolderV2());
 
  
  string key = ObjectToString(info.GetIsolate(), name.As<String>());
 
  
  map<string, string>::iterator iter = obj->find(key);
 
  
 
  
  const string& value = (*iter).second;
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), value.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(value.length())).ToLocalChecked());
}
 
    Local<Name> name, Local<Value> value_obj,
    const PropertyCallbackInfo<void>& info) {
 
  
  map<string, string>* obj = UnwrapMap(info.HolderV2());
 
  
  string key = ObjectToString(info.GetIsolate(), name.As<String>());
  string value = ObjectToString(info.GetIsolate(), value_obj);
 
  
  (*obj)[key] = value;
}
 
Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
    Isolate* isolate) {
  EscapableHandleScope handle_scope(isolate);
 
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
  result->SetInternalFieldCount(1);
  result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
 
  
  return handle_scope.Escape(result);
}
 
 
namespace {
}  
 
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  
  EscapableHandleScope handle_scope(GetIsolate());
 
  
  
  if (request_template_.IsEmpty()) {
    Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
    request_template_.Reset(GetIsolate(), raw_template);
  }
  Local<ObjectTemplate> templ =
      Local<ObjectTemplate>::New(GetIsolate(), request_template_);
 
  
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
 
  
  
  Local<External> request_ptr =
      External::New(GetIsolate(), request, kHttpRequestTag);
 
  
  result->SetInternalField(0, request_ptr);
 
  
  
  
  
  return handle_scope.Escape(result);
}
 
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
  Local<External> field = obj->GetInternalField(0).As<Value>().As<External>();
  void* ptr = field->Value(kHttpRequestTag);
  return static_cast<HttpRequest*>(ptr);
}
 
void JsHttpRequestProcessor::GetPath(Local<Name> name,
                                     const PropertyCallbackInfo<Value>& info) {
  
  HttpRequest* request = UnwrapRequest(info.HolderV2());
 
  
  const string& path = request->Path();
 
  
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
}
 
void JsHttpRequestProcessor::GetReferrer(
    Local<Name> name, const PropertyCallbackInfo<Value>& info) {
  HttpRequest* request = UnwrapRequest(info.HolderV2());
  const string& path = request->Referrer();
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
}
 
void JsHttpRequestProcessor::GetHost(Local<Name> name,
                                     const PropertyCallbackInfo<Value>& info) {
  HttpRequest* request = UnwrapRequest(info.HolderV2());
  const string& path = request->Host();
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
}
 
void JsHttpRequestProcessor::GetUserAgent(
    Local<Name> name, const PropertyCallbackInfo<Value>& info) {
  HttpRequest* request = UnwrapRequest(info.HolderV2());
  const string& path = request->UserAgent();
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
}
 
Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
    Isolate* isolate) {
  EscapableHandleScope handle_scope(isolate);
 
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
  result->SetInternalFieldCount(1);
 
  
  result->SetNativeDataProperty(
      String::NewFromUtf8Literal(isolate, "path", NewStringType::kInternalized),
      GetPath);
  result->SetNativeDataProperty(
      String::NewFromUtf8Literal(isolate, "referrer",
                                 NewStringType::kInternalized),
      GetReferrer);
  result->SetNativeDataProperty(
      String::NewFromUtf8Literal(isolate, "host", NewStringType::kInternalized),
      GetHost);
  result->SetNativeDataProperty(
      String::NewFromUtf8Literal(isolate, "userAgent",
                                 NewStringType::kInternalized),
      GetUserAgent);
 
  
  return handle_scope.Escape(result);
}
 
 
 
 
void HttpRequestProcessor::Log(const char* event) {
  printf("Logged: %s\n", event);
}
 
 
class StringHttpRequest : public HttpRequest {
 public:
  StringHttpRequest(const string& path,
                    const string& referrer,
                    const string& host,
                    const string& user_agent);
  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,
                                     const string& referrer,
                                     const string& host,
                                     const string& user_agent)
    : path_(path),
      referrer_(referrer),
      host_(host),
      user_agent_(user_agent) { }
 
 
void ParseOptions(int argc,
                  char* argv[],
                  map<string, string>* options,
                  string* file) {
  for (int i = 1; i < argc; i++) {
    string arg = argv[i];
    size_t index = arg.find('=', 0);
    if (index == string::npos) {
      *file = arg;
    } else {
      string key = arg.substr(0, index);
      string value = arg.substr(index+1);
      (*options)[key] = value;
    }
  }
}
 
 
MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
  FILE* file = fopen(name.c_str(), "rb");
  if (file == NULL) return MaybeLocal<String>();
 
  fseek(file, 0, SEEK_END);
  size_t size = ftell(file);
  rewind(file);
 
  std::unique_ptr<char[]> chars(new char[size + 1]);
  chars.get()[size] = '\0';
  for (size_t i = 0; i < size;) {
    i += fread(&chars.get()[i], 1, size - i, file);
    if (ferror(file)) {
      fclose(file);
      return MaybeLocal<String>();
    }
  }
  fclose(file);
  MaybeLocal<String> result = String::NewFromUtf8(
      isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size));
  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")
};
 
                    HttpRequestProcessor* processor, int count,
                    StringHttpRequest* reqs) {
  for (int i = 0; i < count; i++) {
    bool result = processor->Process(&reqs[i]);
    if (!result) return false;
  }
  return true;
}
 
void PrintMap(map<string, string>* m) {
  for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
    pair<string, string> entry = *i;
    printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
  }
}
 
 
int main(int argc, char* argv[]) {
  map<string, string> options;
  string file;
  ParseOptions(argc, argv, &options, &file);
  if (file.empty()) {
    fprintf(stderr, "No script was specified.\n");
    return 1;
  }
  Isolate::CreateParams create_params;
  create_params.array_buffer_allocator =
  Isolate* isolate = Isolate::New(create_params);
  Isolate::Scope isolate_scope(isolate);
  HandleScope scope(isolate);
  Local<String> source;
  if (!ReadFile(isolate, file).ToLocal(&source)) {
    fprintf(stderr, "Error reading '%s'.\n", file.c_str());
    return 1;
  }
  JsHttpRequestProcessor processor(isolate, source);
  map<string, string> output;
  if (!processor.Initialize(&options, &output)) {
    fprintf(stderr, "Error initializing processor.\n");
    return 1;
  }
  if (!ProcessEntries(isolate, platform.get(), &processor, kSampleSize,
                      kSampleRequests)) {
    return 1;
  }
  PrintMap(&output);
}
static Allocator * NewDefaultAllocator()
 
Definition: v8-context.h:48
 
Definition: v8-local-handle.h:838
 
Definition: v8-external.h:29
 
Definition: v8-function-callback.h:118
 
Isolate * GetIsolate() const
Definition: v8-function-callback.h:630
 
int Length() const
Definition: v8-function-callback.h:645
 
Definition: v8-template.h:548
 
Definition: v8-function.h:27
 
Definition: v8-persistent-handle.h:349
 
Definition: v8-local-handle.h:119
 
Definition: v8-isolate.h:291
 
Definition: v8-local-handle.h:366
 
static Local< T > New(Isolate *isolate, Local< T > that)
Definition: v8-local-handle.h:448
 
friend class Global
Definition: v8-local-handle.h:468
 
Definition: v8-local-handle.h:734
 
Definition: v8-primitive.h:79
 
Definition: v8-template.h:902
 
Definition: v8-object.h:248
 
Definition: v8-function-callback.h:187
 
Definition: v8-script.h:370
 
Definition: v8-primitive.h:124
 
Definition: v8-exception.h:138
 
static void InitializePlatform(Platform *platform)
 
static bool InitializeICUDefaultLocation(const char *exec_path, const char *icu_data_file=nullptr)
 
static bool Initialize()
Definition: v8-initialization.h:108
 
static void InitializeExternalStartupData(const char *directory_path)
 
Definition: v8-value.h:32
 
uint16_t ExternalPointerTypeTag
Definition: v8-external.h:21
 
NewStringType
Definition: v8-primitive.h:107
 
Intercepted
Definition: v8-template.h:138
 
Definition: v8-template.h:738