// Copyright 2012 the V8 project authors. All rights reserved. // 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. #include #include #include #include #include #include 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; // 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; }; /** * 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* options, map* output) = 0; // Process a single request. virtual bool Process(HttpRequest* req) = 0; static void Log(const char* event); }; /** * 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. JsHttpRequestProcessor(Isolate* isolate, Local script) : isolate_(isolate), script_(script) {} virtual ~JsHttpRequestProcessor(); virtual bool Initialize(map* opts, map* output); virtual bool Process(HttpRequest* req); private: // Execute the script associated with this processor and extract the // Process function. Returns true if this succeeded, otherwise false. bool ExecuteScript(Local script); // Wrap the options and output map in a JavaScript objects and // install it in the global namespace as 'options' and 'output'. bool InstallMaps(map* opts, map* output); // Constructs the template that describes the JavaScript wrapper // type for requests. static Local MakeRequestTemplate(Isolate* isolate); static Local MakeMapTemplate(Isolate* isolate); // Callbacks that access the individual fields of request objects. static void GetPath(Local name, const PropertyCallbackInfo& info); static void GetReferrer(Local name, const PropertyCallbackInfo& info); static void GetHost(Local name, const PropertyCallbackInfo& info); static void GetUserAgent(Local name, const PropertyCallbackInfo& info); // Callbacks that access maps static void MapGet(Local name, const PropertyCallbackInfo& info); static void MapSet(Local name, Local value, const PropertyCallbackInfo& info); // Utility methods for wrapping C++ objects as JavaScript objects, // and going back again. Local WrapMap(map* obj); static map* UnwrapMap(Local obj); Local WrapRequest(HttpRequest* obj); static HttpRequest* UnwrapRequest(Local obj); Isolate* GetIsolate() { return isolate_; } Isolate* isolate_; Local script_; Global context_; Global process_; static Global request_template_; static Global map_template_; }; // ------------------------- // --- P r o c e s s o r --- // ------------------------- static void LogCallback(const v8::FunctionCallbackInfo& args) { if (args.Length() < 1) return; Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); Local arg = args[0]; String::Utf8Value value(isolate, arg); HttpRequestProcessor::Log(*value); } // Execute the script and fetch the Process method. bool JsHttpRequestProcessor::Initialize(map* opts, map* output) { // Create a handle scope to hold the temporary references. HandleScope handle_scope(GetIsolate()); // Create a template for the global object where we set the // built-in global functions. Local global = ObjectTemplate::New(GetIsolate()); global->Set(String::NewFromUtf8(GetIsolate(), "log", NewStringType::kNormal) .ToLocalChecked(), FunctionTemplate::New(GetIsolate(), LogCallback)); // 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. v8::Local context = Context::New(GetIsolate(), NULL, global); context_.Reset(GetIsolate(), context); // Enter the new context so all the following operations take place // within it. Context::Scope context_scope(context); // 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. Local process_name = String::NewFromUtf8(GetIsolate(), "Process", NewStringType::kNormal) .ToLocalChecked(); Local process_val; // If there is no Process function, or if it is not a function, // bail out if (!context->Global()->Get(context, process_name).ToLocal(&process_val) || !process_val->IsFunction()) { return false; } // It is a function; cast it to a Function Local process_fun = Local::Cast(process_val); // Store the function in a Global handle, since we also want // that to remain after this call returns process_.Reset(GetIsolate(), process_fun); // All done; all went well return true; } bool JsHttpRequestProcessor::ExecuteScript(Local script) { HandleScope handle_scope(GetIsolate()); // We're just about to compile the script; set up an error handler to // catch any exceptions the script might throw. TryCatch try_catch(GetIsolate()); Local context(GetIsolate()->GetCurrentContext()); // Compile the script and check for errors. Local