blob: f97869465e7db06315b476e1fbf25e0085495eb7 [file] [log] [blame]
Jason Monkfc934182013-07-22 13:20:39 -04001// Copyright (c) 2010 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Jason Monkfc934182013-07-22 13:20:39 -04005#include "proxy_resolver_v8.h"
6
Jason Monkfc934182013-07-22 13:20:39 -04007#include <algorithm>
Ben Murdoche6933f52014-12-05 12:45:49 +00008#include <cstdio>
9#include <iostream>
10#include <string>
11#include <utils/String8.h>
12#include <v8.h>
Emily Bernier11e292b2015-06-23 16:53:06 -040013#include <libplatform/libplatform.h>
Jason Monkfc934182013-07-22 13:20:39 -040014#include <vector>
15
Ben Murdoche6933f52014-12-05 12:45:49 +000016#include "net_util.h"
17#include "proxy_resolver_script.h"
Jason Monkfc934182013-07-22 13:20:39 -040018
19// Notes on the javascript environment:
20//
21// For the majority of the PAC utility functions, we use the same code
22// as Firefox. See the javascript library that proxy_resolver_scipt.h
23// pulls in.
24//
25// In addition, we implement a subset of Microsoft's extensions to PAC.
26// - myIpAddressEx()
27// - dnsResolveEx()
28// - isResolvableEx()
29// - isInNetEx()
30// - sortIpAddressList()
31//
32// It is worth noting that the original PAC specification does not describe
33// the return values on failure. Consequently, there are compatibility
34// differences between browsers on what to return on failure, which are
35// illustrated below:
36//
37// --------------------+-------------+-------------------+--------------
38// | Firefox3 | InternetExplorer8 | --> Us <---
39// --------------------+-------------+-------------------+--------------
40// myIpAddress() | "127.0.0.1" | ??? | "127.0.0.1"
41// dnsResolve() | null | false | null
42// myIpAddressEx() | N/A | "" | ""
43// sortIpAddressList() | N/A | false | false
44// dnsResolveEx() | N/A | "" | ""
45// isInNetEx() | N/A | false | false
46// --------------------+-------------+-------------------+--------------
47//
48// TODO: The cell above reading ??? means I didn't test it.
49//
50// Another difference is in how dnsResolve() and myIpAddress() are
51// implemented -- whether they should restrict to IPv4 results, or
52// include both IPv4 and IPv6. The following table illustrates the
53// differences:
54//
55// --------------------+-------------+-------------------+--------------
56// | Firefox3 | InternetExplorer8 | --> Us <---
57// --------------------+-------------+-------------------+--------------
58// myIpAddress() | IPv4/IPv6 | IPv4 | IPv4
59// dnsResolve() | IPv4/IPv6 | IPv4 | IPv4
60// isResolvable() | IPv4/IPv6 | IPv4 | IPv4
61// myIpAddressEx() | N/A | IPv4/IPv6 | IPv4/IPv6
62// dnsResolveEx() | N/A | IPv4/IPv6 | IPv4/IPv6
63// sortIpAddressList() | N/A | IPv4/IPv6 | IPv4/IPv6
64// isResolvableEx() | N/A | IPv4/IPv6 | IPv4/IPv6
65// isInNetEx() | N/A | IPv4/IPv6 | IPv4/IPv6
66// -----------------+-------------+-------------------+--------------
67
Jason Monkf5cf6e32013-07-23 17:26:23 -040068static bool DoIsStringASCII(const android::String16& str) {
69 for (size_t i = 0; i < str.size(); i++) {
70 unsigned short c = str.string()[i];
Jason Monkfc934182013-07-22 13:20:39 -040071 if (c > 0x7F)
72 return false;
73 }
74 return true;
75}
76
Jason Monkf5cf6e32013-07-23 17:26:23 -040077bool IsStringASCII(const android::String16& str) {
Jason Monkfc934182013-07-22 13:20:39 -040078 return DoIsStringASCII(str);
79}
80
Jason Monkfc934182013-07-22 13:20:39 -040081namespace net {
82
83namespace {
84
85// Pseudo-name for the PAC script.
86const char kPacResourceName[] = "proxy-pac-script.js";
87// Pseudo-name for the PAC utility script.
88const char kPacUtilityResourceName[] = "proxy-pac-utility-script.js";
89
90// External string wrapper so V8 can access the UTF16 string wrapped by
91// ProxyResolverScriptData.
92class V8ExternalStringFromScriptData
93 : public v8::String::ExternalStringResource {
94 public:
95 explicit V8ExternalStringFromScriptData(
Jason Monkf5cf6e32013-07-23 17:26:23 -040096 const android::String16& script_data)
Jason Monkfc934182013-07-22 13:20:39 -040097 : script_data_(script_data) {}
98
99 virtual const uint16_t* data() const {
Dan Albertd438de82014-11-20 11:20:39 -0800100 return reinterpret_cast<const uint16_t*>(script_data_.string());
Jason Monkfc934182013-07-22 13:20:39 -0400101 }
102
103 virtual size_t length() const {
104 return script_data_.size();
105 }
106
107 private:
Jason Monkf5cf6e32013-07-23 17:26:23 -0400108 const android::String16& script_data_;
Jason Monkfc934182013-07-22 13:20:39 -0400109// DISALLOW_COPY_AND_ASSIGN(V8ExternalStringFromScriptData);
110};
111
112// External string wrapper so V8 can access a string literal.
Torne (Richard Coles)9ae4ac52014-10-22 11:19:47 +0100113class V8ExternalASCIILiteral
114 : public v8::String::ExternalOneByteStringResource {
Jason Monkfc934182013-07-22 13:20:39 -0400115 public:
116 // |ascii| must be a NULL-terminated C string, and must remain valid
117 // throughout this object's lifetime.
118 V8ExternalASCIILiteral(const char* ascii, size_t length)
119 : ascii_(ascii), length_(length) {
Jason Monkfc934182013-07-22 13:20:39 -0400120 }
121
122 virtual const char* data() const {
123 return ascii_;
124 }
125
126 virtual size_t length() const {
127 return length_;
128 }
129
130 private:
131 const char* ascii_;
132 size_t length_;
133};
134
135// When creating a v8::String from a C++ string we have two choices: create
136// a copy, or create a wrapper that shares the same underlying storage.
137// For small strings it is better to just make a copy, whereas for large
138// strings there are savings by sharing the storage. This number identifies
139// the cutoff length for when to start wrapping rather than creating copies.
140const size_t kMaxStringBytesForCopy = 256;
141
142template <class string_type>
143inline typename string_type::value_type* WriteInto(string_type* str,
144 size_t length_with_null) {
145 str->reserve(length_with_null);
146 str->resize(length_with_null - 1);
147 return &((*str)[0]);
148}
149
150// Converts a V8 String to a UTF8 std::string.
151std::string V8StringToUTF8(v8::Handle<v8::String> s) {
152 std::string result;
153 s->WriteUtf8(WriteInto(&result, s->Length() + 1));
154 return result;
155}
156
157// Converts a V8 String to a UTF16 string.
Jason Monkf5cf6e32013-07-23 17:26:23 -0400158android::String16 V8StringToUTF16(v8::Handle<v8::String> s) {
Jason Monkfc934182013-07-22 13:20:39 -0400159 int len = s->Length();
Jason Monkf5cf6e32013-07-23 17:26:23 -0400160 char16_t* buf = new char16_t[len + 1];
Dan Albertd438de82014-11-20 11:20:39 -0800161 s->Write(reinterpret_cast<uint16_t*>(buf), 0, len);
Jason Monkf5cf6e32013-07-23 17:26:23 -0400162 android::String16 ret(buf, len);
Ben Murdochab8377a2016-03-24 15:59:32 +0000163 delete[] buf;
Jason Monkf5cf6e32013-07-23 17:26:23 -0400164 return ret;
165}
166
167std::string UTF16ToASCII(const android::String16& str) {
Jason Monk40adcb52013-08-23 17:19:31 -0400168 android::String8 rstr(str);
169 return std::string(rstr.string());
Jason Monkfc934182013-07-22 13:20:39 -0400170}
171
172// Converts an ASCII std::string to a V8 string.
Jason Monk9fd69be2014-03-18 11:55:59 -0400173v8::Local<v8::String> ASCIIStringToV8String(v8::Isolate* isolate, const std::string& s) {
174 return v8::String::NewFromUtf8(isolate, s.data(), v8::String::kNormalString, s.size());
Jason Monkfc934182013-07-22 13:20:39 -0400175}
176
Jason Monk9fd69be2014-03-18 11:55:59 -0400177v8::Local<v8::String> UTF16StringToV8String(v8::Isolate* isolate, const android::String16& s) {
Dan Albertd438de82014-11-20 11:20:39 -0800178 return v8::String::NewFromTwoByte(
179 isolate, reinterpret_cast<const uint16_t*>(s.string()),
180 v8::String::kNormalString, s.size());
Jason Monkf5cf6e32013-07-23 17:26:23 -0400181}
182
Jason Monkfc934182013-07-22 13:20:39 -0400183// Converts an ASCII string literal to a V8 string.
Jason Monk9fd69be2014-03-18 11:55:59 -0400184v8::Local<v8::String> ASCIILiteralToV8String(v8::Isolate* isolate, const char* ascii) {
Jason Monkfc934182013-07-22 13:20:39 -0400185// DCHECK(IsStringASCII(ascii));
186 size_t length = strlen(ascii);
187 if (length <= kMaxStringBytesForCopy)
Jason Monk9fd69be2014-03-18 11:55:59 -0400188 return v8::String::NewFromUtf8(isolate, ascii, v8::String::kNormalString, length);
189 return v8::String::NewExternal(isolate, new V8ExternalASCIILiteral(ascii, length));
Jason Monkfc934182013-07-22 13:20:39 -0400190}
191
192// Stringizes a V8 object by calling its toString() method. Returns true
193// on success. This may fail if the toString() throws an exception.
194bool V8ObjectToUTF16String(v8::Handle<v8::Value> object,
Jason Monk9fd69be2014-03-18 11:55:59 -0400195 android::String16* utf16_result,
196 v8::Isolate* isolate) {
Jason Monkfc934182013-07-22 13:20:39 -0400197 if (object.IsEmpty())
198 return false;
199
Jason Monk9fd69be2014-03-18 11:55:59 -0400200 v8::HandleScope scope(isolate);
Jason Monkfc934182013-07-22 13:20:39 -0400201 v8::Local<v8::String> str_object = object->ToString();
202 if (str_object.IsEmpty())
203 return false;
204 *utf16_result = V8StringToUTF16(str_object);
205 return true;
206}
207
208// Extracts an hostname argument from |args|. On success returns true
209// and fills |*hostname| with the result.
Jason Monk9fd69be2014-03-18 11:55:59 -0400210bool GetHostnameArgument(const v8::FunctionCallbackInfo<v8::Value>& args, std::string* hostname) {
Jason Monkfc934182013-07-22 13:20:39 -0400211 // The first argument should be a string.
212 if (args.Length() == 0 || args[0].IsEmpty() || !args[0]->IsString())
213 return false;
214
Jason Monkf5cf6e32013-07-23 17:26:23 -0400215 const android::String16 hostname_utf16 = V8StringToUTF16(args[0]->ToString());
Jason Monkfc934182013-07-22 13:20:39 -0400216
217 // If the hostname is already in ASCII, simply return it as is.
218 if (IsStringASCII(hostname_utf16)) {
219 *hostname = UTF16ToASCII(hostname_utf16);
220 return true;
221 }
222 return false;
223}
224
225// Wrapper for passing around IP address strings and IPAddressNumber objects.
226struct IPAddress {
227 IPAddress(const std::string& ip_string, const IPAddressNumber& ip_number)
228 : string_value(ip_string),
229 ip_address_number(ip_number) {
230 }
231
232 // Used for sorting IP addresses in ascending order in SortIpAddressList().
233 // IP6 addresses are placed ahead of IPv4 addresses.
234 bool operator<(const IPAddress& rhs) const {
235 const IPAddressNumber& ip1 = this->ip_address_number;
236 const IPAddressNumber& ip2 = rhs.ip_address_number;
237 if (ip1.size() != ip2.size())
238 return ip1.size() > ip2.size(); // IPv6 before IPv4.
239 return memcmp(&ip1[0], &ip2[0], ip1.size()) < 0; // Ascending order.
240 }
241
242 std::string string_value;
243 IPAddressNumber ip_address_number;
244};
245
246template<typename STR>
247bool RemoveCharsT(const STR& input,
248 const typename STR::value_type remove_chars[],
249 STR* output) {
250 bool removed = false;
251 size_t found;
252
253 *output = input;
254
255 found = output->find_first_of(remove_chars);
256 while (found != STR::npos) {
257 removed = true;
258 output->replace(found, 1, STR());
259 found = output->find_first_of(remove_chars, found);
260 }
261
262 return removed;
263}
264
Jason Monkfc934182013-07-22 13:20:39 -0400265bool RemoveChars(const std::string& input,
266 const char remove_chars[],
267 std::string* output) {
268 return RemoveCharsT(input, remove_chars, output);
269}
270
271// Handler for "sortIpAddressList(IpAddressList)". |ip_address_list| is a
272// semi-colon delimited string containing IP addresses.
273// |sorted_ip_address_list| is the resulting list of sorted semi-colon delimited
274// IP addresses or an empty string if unable to sort the IP address list.
275// Returns 'true' if the sorting was successful, and 'false' if the input was an
276// empty string, a string of separators (";" in this case), or if any of the IP
277// addresses in the input list failed to parse.
278bool SortIpAddressList(const std::string& ip_address_list,
279 std::string* sorted_ip_address_list) {
280 sorted_ip_address_list->clear();
281
282 // Strip all whitespace (mimics IE behavior).
283 std::string cleaned_ip_address_list;
284 RemoveChars(ip_address_list, " \t", &cleaned_ip_address_list);
285 if (cleaned_ip_address_list.empty())
286 return false;
287
288 // Split-up IP addresses and store them in a vector.
289 std::vector<IPAddress> ip_vector;
290 IPAddressNumber ip_num;
291 char *tok_list = strtok((char *)cleaned_ip_address_list.c_str(), ";");
292 while (tok_list != NULL) {
293 if (!ParseIPLiteralToNumber(tok_list, &ip_num))
294 return false;
295 ip_vector.push_back(IPAddress(tok_list, ip_num));
Jason Monk86b75a52013-08-23 17:10:51 -0400296 tok_list = strtok(NULL, ";");
Jason Monkfc934182013-07-22 13:20:39 -0400297 }
298
299 if (ip_vector.empty()) // Can happen if we have something like
300 return false; // sortIpAddressList(";") or sortIpAddressList("; ;")
301
302 // Sort lists according to ascending numeric value.
303 if (ip_vector.size() > 1)
304 std::stable_sort(ip_vector.begin(), ip_vector.end());
305
306 // Return a semi-colon delimited list of sorted addresses (IPv6 followed by
307 // IPv4).
308 for (size_t i = 0; i < ip_vector.size(); ++i) {
309 if (i > 0)
310 *sorted_ip_address_list += ";";
311 *sorted_ip_address_list += ip_vector[i].string_value;
312 }
313 return true;
314}
315
316
317// Handler for "isInNetEx(ip_address, ip_prefix)". |ip_address| is a string
318// containing an IPv4/IPv6 address, and |ip_prefix| is a string containg a
319// slash-delimited IP prefix with the top 'n' bits specified in the bit
320// field. This returns 'true' if the address is in the same subnet, and
321// 'false' otherwise. Also returns 'false' if the prefix is in an incorrect
322// format, or if an address and prefix of different types are used (e.g. IPv6
323// address and IPv4 prefix).
324bool IsInNetEx(const std::string& ip_address, const std::string& ip_prefix) {
325 IPAddressNumber address;
Jason Monkeafc0fa2013-08-23 17:05:52 -0400326 std::string cleaned_ip_address;
327 if (RemoveChars(ip_address, " \t", &cleaned_ip_address))
328 return false;
Jason Monkfc934182013-07-22 13:20:39 -0400329 if (!ParseIPLiteralToNumber(ip_address, &address))
330 return false;
331
332 IPAddressNumber prefix;
333 size_t prefix_length_in_bits;
334 if (!ParseCIDRBlock(ip_prefix, &prefix, &prefix_length_in_bits))
335 return false;
336
337 // Both |address| and |prefix| must be of the same type (IPv4 or IPv6).
338 if (address.size() != prefix.size())
339 return false;
340
341 return IPNumberMatchesPrefix(address, prefix, prefix_length_in_bits);
342}
343
344} // namespace
345
Ben Murdochab8377a2016-03-24 15:59:32 +0000346class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
347 public:
348 virtual void* Allocate(size_t length) {
349 void* data = AllocateUninitialized(length);
350 return data == NULL ? data : memset(data, 0, length);
351 }
352 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
353 virtual void Free(void* data, size_t) { free(data); }
354};
355
356
Jason Monkfc934182013-07-22 13:20:39 -0400357// ProxyResolverV8::Context ---------------------------------------------------
358
359class ProxyResolverV8::Context {
360 public:
Jason Monkf5cf6e32013-07-23 17:26:23 -0400361 explicit Context(ProxyResolverJSBindings* js_bindings,
Jason Monk9fd69be2014-03-18 11:55:59 -0400362 ProxyErrorListener* error_listener, v8::Isolate* isolate)
363 : js_bindings_(js_bindings), error_listener_(error_listener), isolate_(isolate) {
Jason Monkfc934182013-07-22 13:20:39 -0400364 }
365
366 ~Context() {
Jason Monk9fd69be2014-03-18 11:55:59 -0400367 v8::Locker locked(isolate_);
368 v8::Isolate::Scope isolate_scope(isolate_);
Jason Monkfc934182013-07-22 13:20:39 -0400369
Jason Monk9fd69be2014-03-18 11:55:59 -0400370 v8_this_.Reset();
371 v8_context_.Reset();
Jason Monkfc934182013-07-22 13:20:39 -0400372 }
373
Jason Monk40adcb52013-08-23 17:19:31 -0400374 int ResolveProxy(const android::String16 url, const android::String16 host,
375 android::String16* results) {
Jason Monk9fd69be2014-03-18 11:55:59 -0400376 v8::Locker locked(isolate_);
377 v8::Isolate::Scope isolate_scope(isolate_);
378 v8::HandleScope scope(isolate_);
Jason Monkfc934182013-07-22 13:20:39 -0400379
Jason Monk9fd69be2014-03-18 11:55:59 -0400380 v8::Local<v8::Context> context =
381 v8::Local<v8::Context>::New(isolate_, v8_context_);
382 v8::Context::Scope function_scope(context);
Jason Monkfc934182013-07-22 13:20:39 -0400383
384 v8::Local<v8::Value> function;
385 if (!GetFindProxyForURL(&function)) {
Jason Monk40adcb52013-08-23 17:19:31 -0400386 error_listener_->ErrorMessage(
387 android::String16("FindProxyForURL() is undefined"));
Jason Monkfc934182013-07-22 13:20:39 -0400388 return ERR_PAC_SCRIPT_FAILED;
389 }
390
391 v8::Handle<v8::Value> argv[] = {
Jason Monk9fd69be2014-03-18 11:55:59 -0400392 UTF16StringToV8String(isolate_, url),
393 UTF16StringToV8String(isolate_, host) };
Jason Monkfc934182013-07-22 13:20:39 -0400394
395 v8::TryCatch try_catch;
396 v8::Local<v8::Value> ret = v8::Function::Cast(*function)->Call(
Jason Monk9fd69be2014-03-18 11:55:59 -0400397 context->Global(), 2, argv);
Jason Monkfc934182013-07-22 13:20:39 -0400398
399 if (try_catch.HasCaught()) {
Jason Monk40adcb52013-08-23 17:19:31 -0400400 error_listener_->ErrorMessage(
401 V8StringToUTF16(try_catch.Message()->Get()));
Jason Monkfc934182013-07-22 13:20:39 -0400402 return ERR_PAC_SCRIPT_FAILED;
403 }
404
405 if (!ret->IsString()) {
Jason Monk40adcb52013-08-23 17:19:31 -0400406 error_listener_->ErrorMessage(
407 android::String16("FindProxyForURL() did not return a string."));
Jason Monkfc934182013-07-22 13:20:39 -0400408 return ERR_PAC_SCRIPT_FAILED;
409 }
410
Jason Monkf5cf6e32013-07-23 17:26:23 -0400411 *results = V8StringToUTF16(ret->ToString());
Jason Monkfc934182013-07-22 13:20:39 -0400412
Jason Monkf5cf6e32013-07-23 17:26:23 -0400413 if (!IsStringASCII(*results)) {
Jason Monkfc934182013-07-22 13:20:39 -0400414 // TODO: Rather than failing when a wide string is returned, we
415 // could extend the parsing to handle IDNA hostnames by
416 // converting them to ASCII punycode.
417 // crbug.com/47234
Jason Monk40adcb52013-08-23 17:19:31 -0400418 error_listener_->ErrorMessage(
419 android::String16("FindProxyForURL() returned a non-ASCII string"));
Jason Monkfc934182013-07-22 13:20:39 -0400420 return ERR_PAC_SCRIPT_FAILED;
421 }
422
Jason Monkfc934182013-07-22 13:20:39 -0400423 return OK;
424 }
425
Jason Monkf5cf6e32013-07-23 17:26:23 -0400426 int InitV8(const android::String16& pac_script) {
Jason Monk9fd69be2014-03-18 11:55:59 -0400427 v8::Locker locked(isolate_);
428 v8::Isolate::Scope isolate_scope(isolate_);
429 v8::HandleScope scope(isolate_);
Jason Monkfc934182013-07-22 13:20:39 -0400430
Jason Monk9fd69be2014-03-18 11:55:59 -0400431 v8_this_.Reset(isolate_, v8::External::New(isolate_, this));
432 v8::Local<v8::External> v8_this =
433 v8::Local<v8::External>::New(isolate_, v8_this_);
Jason Monkfc934182013-07-22 13:20:39 -0400434 v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
435
436 // Attach the javascript bindings.
437 v8::Local<v8::FunctionTemplate> alert_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400438 v8::FunctionTemplate::New(isolate_, &AlertCallback, v8_this);
439 global_template->Set(ASCIILiteralToV8String(isolate_, "alert"), alert_template);
Jason Monkfc934182013-07-22 13:20:39 -0400440
441 v8::Local<v8::FunctionTemplate> my_ip_address_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400442 v8::FunctionTemplate::New(isolate_, &MyIpAddressCallback, v8_this);
443 global_template->Set(ASCIILiteralToV8String(isolate_, "myIpAddress"),
Jason Monkfc934182013-07-22 13:20:39 -0400444 my_ip_address_template);
445
446 v8::Local<v8::FunctionTemplate> dns_resolve_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400447 v8::FunctionTemplate::New(isolate_, &DnsResolveCallback, v8_this);
448 global_template->Set(ASCIILiteralToV8String(isolate_, "dnsResolve"),
Jason Monkfc934182013-07-22 13:20:39 -0400449 dns_resolve_template);
450
451 // Microsoft's PAC extensions:
452
453 v8::Local<v8::FunctionTemplate> dns_resolve_ex_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400454 v8::FunctionTemplate::New(isolate_, &DnsResolveExCallback, v8_this);
455 global_template->Set(ASCIILiteralToV8String(isolate_, "dnsResolveEx"),
Jason Monkfc934182013-07-22 13:20:39 -0400456 dns_resolve_ex_template);
457
458 v8::Local<v8::FunctionTemplate> my_ip_address_ex_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400459 v8::FunctionTemplate::New(isolate_, &MyIpAddressExCallback, v8_this);
460 global_template->Set(ASCIILiteralToV8String(isolate_, "myIpAddressEx"),
Jason Monkfc934182013-07-22 13:20:39 -0400461 my_ip_address_ex_template);
462
463 v8::Local<v8::FunctionTemplate> sort_ip_address_list_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400464 v8::FunctionTemplate::New(isolate_, &SortIpAddressListCallback, v8_this);
465 global_template->Set(ASCIILiteralToV8String(isolate_, "sortIpAddressList"),
Jason Monkfc934182013-07-22 13:20:39 -0400466 sort_ip_address_list_template);
467
468 v8::Local<v8::FunctionTemplate> is_in_net_ex_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400469 v8::FunctionTemplate::New(isolate_, &IsInNetExCallback, v8_this);
470 global_template->Set(ASCIILiteralToV8String(isolate_, "isInNetEx"),
Jason Monkfc934182013-07-22 13:20:39 -0400471 is_in_net_ex_template);
472
Jason Monk9fd69be2014-03-18 11:55:59 -0400473 v8_context_.Reset(
474 isolate_, v8::Context::New(isolate_, NULL, global_template));
Jason Monkfc934182013-07-22 13:20:39 -0400475
Jason Monk9fd69be2014-03-18 11:55:59 -0400476 v8::Local<v8::Context> context =
477 v8::Local<v8::Context>::New(isolate_, v8_context_);
478 v8::Context::Scope ctx(context);
Jason Monkfc934182013-07-22 13:20:39 -0400479
480 // Add the PAC utility functions to the environment.
481 // (This script should never fail, as it is a string literal!)
482 // Note that the two string literals are concatenated.
483 int rv = RunScript(
Jason Monk9fd69be2014-03-18 11:55:59 -0400484 ASCIILiteralToV8String(isolate_,
Jason Monkfc934182013-07-22 13:20:39 -0400485 PROXY_RESOLVER_SCRIPT
486 PROXY_RESOLVER_SCRIPT_EX),
487 kPacUtilityResourceName);
488 if (rv != OK) {
489 return rv;
490 }
491
492 // Add the user's PAC code to the environment.
Jason Monk9fd69be2014-03-18 11:55:59 -0400493 rv = RunScript(UTF16StringToV8String(isolate_, pac_script), kPacResourceName);
Jason Monkfc934182013-07-22 13:20:39 -0400494 if (rv != OK) {
495 return rv;
496 }
497
498 // At a minimum, the FindProxyForURL() function must be defined for this
499 // to be a legitimiate PAC script.
500 v8::Local<v8::Value> function;
501 if (!GetFindProxyForURL(&function))
502 return ERR_PAC_SCRIPT_FAILED;
503
504 return OK;
505 }
506
507 void PurgeMemory() {
Jason Monk9fd69be2014-03-18 11:55:59 -0400508 v8::Locker locked(isolate_);
509 v8::Isolate::Scope isolate_scope(isolate_);
Ben Murdoche80b5fa2014-07-31 16:47:35 +0100510 isolate_->LowMemoryNotification();
Jason Monkfc934182013-07-22 13:20:39 -0400511 }
512
513 private:
514 bool GetFindProxyForURL(v8::Local<v8::Value>* function) {
Jason Monk9fd69be2014-03-18 11:55:59 -0400515 v8::Local<v8::Context> context =
516 v8::Local<v8::Context>::New(isolate_, v8_context_);
517 *function = context->Global()->Get(
518 ASCIILiteralToV8String(isolate_, "FindProxyForURL"));
Jason Monkfc934182013-07-22 13:20:39 -0400519 return (*function)->IsFunction();
520 }
521
522 // Handle an exception thrown by V8.
523 void HandleError(v8::Handle<v8::Message> message) {
524 if (message.IsEmpty())
525 return;
Jason Monkf5cf6e32013-07-23 17:26:23 -0400526 error_listener_->ErrorMessage(V8StringToUTF16(message->Get()));
Jason Monkfc934182013-07-22 13:20:39 -0400527 }
528
529 // Compiles and runs |script| in the current V8 context.
530 // Returns OK on success, otherwise an error code.
531 int RunScript(v8::Handle<v8::String> script, const char* script_name) {
532 v8::TryCatch try_catch;
533
534 // Compile the script.
535 v8::ScriptOrigin origin =
Jason Monk9fd69be2014-03-18 11:55:59 -0400536 v8::ScriptOrigin(ASCIILiteralToV8String(isolate_, script_name));
Jason Monkfc934182013-07-22 13:20:39 -0400537 v8::Local<v8::Script> code = v8::Script::Compile(script, &origin);
538
539 // Execute.
540 if (!code.IsEmpty())
541 code->Run();
542
543 // Check for errors.
544 if (try_catch.HasCaught()) {
545 HandleError(try_catch.Message());
546 return ERR_PAC_SCRIPT_FAILED;
547 }
548
549 return OK;
550 }
551
552 // V8 callback for when "alert()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400553 static void AlertCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400554 Context* context =
555 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
556
557 // Like firefox we assume "undefined" if no argument was specified, and
558 // disregard any arguments beyond the first.
Jason Monkf5cf6e32013-07-23 17:26:23 -0400559 android::String16 message;
Jason Monkfc934182013-07-22 13:20:39 -0400560 if (args.Length() == 0) {
561 std::string undef = "undefined";
Jason Monkf5cf6e32013-07-23 17:26:23 -0400562 android::String8 undef8(undef.c_str());
563 android::String16 wundef(undef8);
Jason Monkfc934182013-07-22 13:20:39 -0400564 message = wundef;
565 } else {
Jason Monk9fd69be2014-03-18 11:55:59 -0400566 if (!V8ObjectToUTF16String(args[0], &message, args.GetIsolate()))
567 return; // toString() threw an exception.
Jason Monkfc934182013-07-22 13:20:39 -0400568 }
569
Jason Monkf5cf6e32013-07-23 17:26:23 -0400570 context->error_listener_->AlertMessage(message);
Jason Monk9fd69be2014-03-18 11:55:59 -0400571 return;
Jason Monkfc934182013-07-22 13:20:39 -0400572 }
573
574 // V8 callback for when "myIpAddress()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400575 static void MyIpAddressCallback(
576 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400577 Context* context =
578 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
579
580 std::string result;
581 bool success;
582
583 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400584 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400585
586 // We shouldn't be called with any arguments, but will not complain if
587 // we are.
588 success = context->js_bindings_->MyIpAddress(&result);
589 }
590
Jason Monk9fd69be2014-03-18 11:55:59 -0400591 if (!success) {
592 args.GetReturnValue().Set(ASCIILiteralToV8String(args.GetIsolate(), "127.0.0.1"));
593 } else {
594 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), result));
595 }
Jason Monkfc934182013-07-22 13:20:39 -0400596 }
597
598 // V8 callback for when "myIpAddressEx()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400599 static void MyIpAddressExCallback(
600 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400601 Context* context =
602 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
603
604 std::string ip_address_list;
605 bool success;
606
607 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400608 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400609
610 // We shouldn't be called with any arguments, but will not complain if
611 // we are.
612 success = context->js_bindings_->MyIpAddressEx(&ip_address_list);
613 }
614
615 if (!success)
616 ip_address_list = std::string();
Jason Monk9fd69be2014-03-18 11:55:59 -0400617 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), ip_address_list));
Jason Monkfc934182013-07-22 13:20:39 -0400618 }
619
620 // V8 callback for when "dnsResolve()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400621 static void DnsResolveCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400622 Context* context =
623 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
624
625 // We need at least one string argument.
626 std::string hostname;
Jason Monk9fd69be2014-03-18 11:55:59 -0400627 if (!GetHostnameArgument(args, &hostname)) {
628 return;
629 }
Jason Monkfc934182013-07-22 13:20:39 -0400630
631 std::string ip_address;
632 bool success;
633
634 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400635 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400636 success = context->js_bindings_->DnsResolve(hostname, &ip_address);
637 }
638
Jason Monk9fd69be2014-03-18 11:55:59 -0400639 if (success) {
640 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), ip_address));
641 } else {
642 args.GetReturnValue().SetNull();
643 }
Jason Monkfc934182013-07-22 13:20:39 -0400644 }
645
646 // V8 callback for when "dnsResolveEx()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400647 static void DnsResolveExCallback(
648 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400649 Context* context =
650 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
651
652 // We need at least one string argument.
653 std::string hostname;
Jason Monk9fd69be2014-03-18 11:55:59 -0400654 if (!GetHostnameArgument(args, &hostname)) {
655 args.GetReturnValue().SetNull();
656 return;
657 }
Jason Monkfc934182013-07-22 13:20:39 -0400658
659 std::string ip_address_list;
660 bool success;
661
662 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400663 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400664 success = context->js_bindings_->DnsResolveEx(hostname, &ip_address_list);
665 }
666
667 if (!success)
668 ip_address_list = std::string();
669
Jason Monk9fd69be2014-03-18 11:55:59 -0400670 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), ip_address_list));
Jason Monkfc934182013-07-22 13:20:39 -0400671 }
672
673 // V8 callback for when "sortIpAddressList()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400674 static void SortIpAddressListCallback(
675 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400676 // We need at least one string argument.
Jason Monk9fd69be2014-03-18 11:55:59 -0400677 if (args.Length() == 0 || args[0].IsEmpty() || !args[0]->IsString()) {
678 args.GetReturnValue().SetNull();
679 return;
680 }
Jason Monkfc934182013-07-22 13:20:39 -0400681
682 std::string ip_address_list = V8StringToUTF8(args[0]->ToString());
683 std::string sorted_ip_address_list;
684 bool success = SortIpAddressList(ip_address_list, &sorted_ip_address_list);
Jason Monk9fd69be2014-03-18 11:55:59 -0400685 if (!success) {
686 args.GetReturnValue().Set(false);
687 return;
688 }
689 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), sorted_ip_address_list));
Jason Monkfc934182013-07-22 13:20:39 -0400690 }
691
692 // V8 callback for when "isInNetEx()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400693 static void IsInNetExCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400694 // We need at least 2 string arguments.
695 if (args.Length() < 2 || args[0].IsEmpty() || !args[0]->IsString() ||
Jason Monk9fd69be2014-03-18 11:55:59 -0400696 args[1].IsEmpty() || !args[1]->IsString()) {
697 args.GetReturnValue().SetNull();
698 return;
699 }
Jason Monkfc934182013-07-22 13:20:39 -0400700
701 std::string ip_address = V8StringToUTF8(args[0]->ToString());
702 std::string ip_prefix = V8StringToUTF8(args[1]->ToString());
Jason Monk9fd69be2014-03-18 11:55:59 -0400703 args.GetReturnValue().Set(IsInNetEx(ip_address, ip_prefix));
Jason Monkfc934182013-07-22 13:20:39 -0400704 }
705
706 ProxyResolverJSBindings* js_bindings_;
Jason Monkf5cf6e32013-07-23 17:26:23 -0400707 ProxyErrorListener* error_listener_;
Jason Monk9fd69be2014-03-18 11:55:59 -0400708 v8::Isolate* isolate_;
Jason Monkfc934182013-07-22 13:20:39 -0400709 v8::Persistent<v8::External> v8_this_;
710 v8::Persistent<v8::Context> v8_context_;
711};
712
713// ProxyResolverV8 ------------------------------------------------------------
714
Ben Murdochab8377a2016-03-24 15:59:32 +0000715bool ProxyResolverV8::initialized_for_this_process_ = false;
716
Jason Monkfc934182013-07-22 13:20:39 -0400717ProxyResolverV8::ProxyResolverV8(
Jason Monkf5cf6e32013-07-23 17:26:23 -0400718 ProxyResolverJSBindings* custom_js_bindings,
719 ProxyErrorListener* error_listener)
720 : context_(NULL), js_bindings_(custom_js_bindings),
721 error_listener_(error_listener) {
Ben Murdochab8377a2016-03-24 15:59:32 +0000722 if (!initialized_for_this_process_) {
Emily Bernier11e292b2015-06-23 16:53:06 -0400723 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
724 v8::V8::InitializePlatform(platform);
725 v8::V8::Initialize();
Ben Murdochab8377a2016-03-24 15:59:32 +0000726 initialized_for_this_process_ = true;
Emily Bernier11e292b2015-06-23 16:53:06 -0400727 }
Jason Monkfc934182013-07-22 13:20:39 -0400728}
729
730ProxyResolverV8::~ProxyResolverV8() {
Jason Monkc06a8d62013-08-19 10:36:23 -0400731 if (context_ != NULL) {
732 delete context_;
733 context_ = NULL;
734 }
735 if (js_bindings_ != NULL) {
736 delete js_bindings_;
737 }
Jason Monkfc934182013-07-22 13:20:39 -0400738}
739
Jason Monkf5cf6e32013-07-23 17:26:23 -0400740int ProxyResolverV8::GetProxyForURL(const android::String16 spec, const android::String16 host,
741 android::String16* results) {
Jason Monkfc934182013-07-22 13:20:39 -0400742 // If the V8 instance has not been initialized (either because
743 // SetPacScript() wasn't called yet, or because it failed.
744 if (context_ == NULL)
745 return ERR_FAILED;
746
747 // Otherwise call into V8.
748 int rv = context_->ResolveProxy(spec, host, results);
749
750 return rv;
751}
752
Jason Monkfc934182013-07-22 13:20:39 -0400753void ProxyResolverV8::PurgeMemory() {
754 context_->PurgeMemory();
755}
756
Jason Monk40adcb52013-08-23 17:19:31 -0400757int ProxyResolverV8::SetPacScript(const android::String16& script_data) {
Jason Monkfc934182013-07-22 13:20:39 -0400758 if (context_ != NULL) {
759 delete context_;
Jason Monkc06a8d62013-08-19 10:36:23 -0400760 context_ = NULL;
Jason Monkfc934182013-07-22 13:20:39 -0400761 }
Jason Monkf5cf6e32013-07-23 17:26:23 -0400762 if (script_data.size() == 0)
Jason Monkfc934182013-07-22 13:20:39 -0400763 return ERR_PAC_SCRIPT_FAILED;
764
765 // Try parsing the PAC script.
Ben Murdochab8377a2016-03-24 15:59:32 +0000766 ArrayBufferAllocator allocator;
767 v8::Isolate::CreateParams create_params;
768 create_params.array_buffer_allocator = &allocator;
769
770 context_ = new Context(js_bindings_, error_listener_, v8::Isolate::New(create_params));
Jason Monkfc934182013-07-22 13:20:39 -0400771 int rv;
772 if ((rv = context_->InitV8(script_data)) != OK) {
773 context_ = NULL;
774 }
775 if (rv != OK)
776 context_ = NULL;
777 return rv;
778}
779
780} // namespace net