blob: 4d43253655594864ead1d468738de43e4d8e2538 [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
5#include <algorithm>
6#include <cstdio>
7#include <string>
8
Jason Monkf5cf6e32013-07-23 17:26:23 -04009#include <utils/String16.h>
10
Jason Monkfc934182013-07-22 13:20:39 -040011#include "proxy_resolver_v8.h"
12
13#include "proxy_resolver_script.h"
14#include "net_util.h"
15#include <include/v8.h>
16#include <algorithm>
17#include <vector>
18
19#include <iostream>
20
21#include <string.h>
Jason Monkf5cf6e32013-07-23 17:26:23 -040022#include <utils/String8.h>
23#include <utils/String16.h>
Jason Monkfc934182013-07-22 13:20:39 -040024
25// Notes on the javascript environment:
26//
27// For the majority of the PAC utility functions, we use the same code
28// as Firefox. See the javascript library that proxy_resolver_scipt.h
29// pulls in.
30//
31// In addition, we implement a subset of Microsoft's extensions to PAC.
32// - myIpAddressEx()
33// - dnsResolveEx()
34// - isResolvableEx()
35// - isInNetEx()
36// - sortIpAddressList()
37//
38// It is worth noting that the original PAC specification does not describe
39// the return values on failure. Consequently, there are compatibility
40// differences between browsers on what to return on failure, which are
41// illustrated below:
42//
43// --------------------+-------------+-------------------+--------------
44// | Firefox3 | InternetExplorer8 | --> Us <---
45// --------------------+-------------+-------------------+--------------
46// myIpAddress() | "127.0.0.1" | ??? | "127.0.0.1"
47// dnsResolve() | null | false | null
48// myIpAddressEx() | N/A | "" | ""
49// sortIpAddressList() | N/A | false | false
50// dnsResolveEx() | N/A | "" | ""
51// isInNetEx() | N/A | false | false
52// --------------------+-------------+-------------------+--------------
53//
54// TODO: The cell above reading ??? means I didn't test it.
55//
56// Another difference is in how dnsResolve() and myIpAddress() are
57// implemented -- whether they should restrict to IPv4 results, or
58// include both IPv4 and IPv6. The following table illustrates the
59// differences:
60//
61// --------------------+-------------+-------------------+--------------
62// | Firefox3 | InternetExplorer8 | --> Us <---
63// --------------------+-------------+-------------------+--------------
64// myIpAddress() | IPv4/IPv6 | IPv4 | IPv4
65// dnsResolve() | IPv4/IPv6 | IPv4 | IPv4
66// isResolvable() | IPv4/IPv6 | IPv4 | IPv4
67// myIpAddressEx() | N/A | IPv4/IPv6 | IPv4/IPv6
68// dnsResolveEx() | N/A | IPv4/IPv6 | IPv4/IPv6
69// sortIpAddressList() | N/A | IPv4/IPv6 | IPv4/IPv6
70// isResolvableEx() | N/A | IPv4/IPv6 | IPv4/IPv6
71// isInNetEx() | N/A | IPv4/IPv6 | IPv4/IPv6
72// -----------------+-------------+-------------------+--------------
73
Jason Monkf5cf6e32013-07-23 17:26:23 -040074static bool DoIsStringASCII(const android::String16& str) {
75 for (size_t i = 0; i < str.size(); i++) {
76 unsigned short c = str.string()[i];
Jason Monkfc934182013-07-22 13:20:39 -040077 if (c > 0x7F)
78 return false;
79 }
80 return true;
81}
82
Jason Monkf5cf6e32013-07-23 17:26:23 -040083bool IsStringASCII(const android::String16& str) {
Jason Monkfc934182013-07-22 13:20:39 -040084 return DoIsStringASCII(str);
85}
86
Jason Monkfc934182013-07-22 13:20:39 -040087namespace net {
88
89namespace {
90
91// Pseudo-name for the PAC script.
92const char kPacResourceName[] = "proxy-pac-script.js";
93// Pseudo-name for the PAC utility script.
94const char kPacUtilityResourceName[] = "proxy-pac-utility-script.js";
95
96// External string wrapper so V8 can access the UTF16 string wrapped by
97// ProxyResolverScriptData.
98class V8ExternalStringFromScriptData
99 : public v8::String::ExternalStringResource {
100 public:
101 explicit V8ExternalStringFromScriptData(
Jason Monkf5cf6e32013-07-23 17:26:23 -0400102 const android::String16& script_data)
Jason Monkfc934182013-07-22 13:20:39 -0400103 : script_data_(script_data) {}
104
105 virtual const uint16_t* data() const {
Jason Monkf5cf6e32013-07-23 17:26:23 -0400106 return script_data_.string();
Jason Monkfc934182013-07-22 13:20:39 -0400107 }
108
109 virtual size_t length() const {
110 return script_data_.size();
111 }
112
113 private:
Jason Monkf5cf6e32013-07-23 17:26:23 -0400114 const android::String16& script_data_;
Jason Monkfc934182013-07-22 13:20:39 -0400115// DISALLOW_COPY_AND_ASSIGN(V8ExternalStringFromScriptData);
116};
117
118// External string wrapper so V8 can access a string literal.
Torne (Richard Coles)9ae4ac52014-10-22 11:19:47 +0100119class V8ExternalASCIILiteral
120 : public v8::String::ExternalOneByteStringResource {
Jason Monkfc934182013-07-22 13:20:39 -0400121 public:
122 // |ascii| must be a NULL-terminated C string, and must remain valid
123 // throughout this object's lifetime.
124 V8ExternalASCIILiteral(const char* ascii, size_t length)
125 : ascii_(ascii), length_(length) {
Jason Monkfc934182013-07-22 13:20:39 -0400126 }
127
128 virtual const char* data() const {
129 return ascii_;
130 }
131
132 virtual size_t length() const {
133 return length_;
134 }
135
136 private:
137 const char* ascii_;
138 size_t length_;
139};
140
141// When creating a v8::String from a C++ string we have two choices: create
142// a copy, or create a wrapper that shares the same underlying storage.
143// For small strings it is better to just make a copy, whereas for large
144// strings there are savings by sharing the storage. This number identifies
145// the cutoff length for when to start wrapping rather than creating copies.
146const size_t kMaxStringBytesForCopy = 256;
147
148template <class string_type>
149inline typename string_type::value_type* WriteInto(string_type* str,
150 size_t length_with_null) {
151 str->reserve(length_with_null);
152 str->resize(length_with_null - 1);
153 return &((*str)[0]);
154}
155
156// Converts a V8 String to a UTF8 std::string.
157std::string V8StringToUTF8(v8::Handle<v8::String> s) {
158 std::string result;
159 s->WriteUtf8(WriteInto(&result, s->Length() + 1));
160 return result;
161}
162
163// Converts a V8 String to a UTF16 string.
Jason Monkf5cf6e32013-07-23 17:26:23 -0400164android::String16 V8StringToUTF16(v8::Handle<v8::String> s) {
Jason Monkfc934182013-07-22 13:20:39 -0400165 int len = s->Length();
Jason Monkf5cf6e32013-07-23 17:26:23 -0400166 char16_t* buf = new char16_t[len + 1];
167 s->Write(buf, 0, len);
168 android::String16 ret(buf, len);
169 delete buf;
170 return ret;
171}
172
173std::string UTF16ToASCII(const android::String16& str) {
Jason Monk40adcb52013-08-23 17:19:31 -0400174 android::String8 rstr(str);
175 return std::string(rstr.string());
Jason Monkfc934182013-07-22 13:20:39 -0400176}
177
178// Converts an ASCII std::string to a V8 string.
Jason Monk9fd69be2014-03-18 11:55:59 -0400179v8::Local<v8::String> ASCIIStringToV8String(v8::Isolate* isolate, const std::string& s) {
180 return v8::String::NewFromUtf8(isolate, s.data(), v8::String::kNormalString, s.size());
Jason Monkfc934182013-07-22 13:20:39 -0400181}
182
Jason Monk9fd69be2014-03-18 11:55:59 -0400183v8::Local<v8::String> UTF16StringToV8String(v8::Isolate* isolate, const android::String16& s) {
184 return v8::String::NewFromTwoByte(isolate, s.string(), v8::String::kNormalString, s.size());
Jason Monkf5cf6e32013-07-23 17:26:23 -0400185}
186
Jason Monkfc934182013-07-22 13:20:39 -0400187// Converts an ASCII string literal to a V8 string.
Jason Monk9fd69be2014-03-18 11:55:59 -0400188v8::Local<v8::String> ASCIILiteralToV8String(v8::Isolate* isolate, const char* ascii) {
Jason Monkfc934182013-07-22 13:20:39 -0400189// DCHECK(IsStringASCII(ascii));
190 size_t length = strlen(ascii);
191 if (length <= kMaxStringBytesForCopy)
Jason Monk9fd69be2014-03-18 11:55:59 -0400192 return v8::String::NewFromUtf8(isolate, ascii, v8::String::kNormalString, length);
193 return v8::String::NewExternal(isolate, new V8ExternalASCIILiteral(ascii, length));
Jason Monkfc934182013-07-22 13:20:39 -0400194}
195
196// Stringizes a V8 object by calling its toString() method. Returns true
197// on success. This may fail if the toString() throws an exception.
198bool V8ObjectToUTF16String(v8::Handle<v8::Value> object,
Jason Monk9fd69be2014-03-18 11:55:59 -0400199 android::String16* utf16_result,
200 v8::Isolate* isolate) {
Jason Monkfc934182013-07-22 13:20:39 -0400201 if (object.IsEmpty())
202 return false;
203
Jason Monk9fd69be2014-03-18 11:55:59 -0400204 v8::HandleScope scope(isolate);
Jason Monkfc934182013-07-22 13:20:39 -0400205 v8::Local<v8::String> str_object = object->ToString();
206 if (str_object.IsEmpty())
207 return false;
208 *utf16_result = V8StringToUTF16(str_object);
209 return true;
210}
211
212// Extracts an hostname argument from |args|. On success returns true
213// and fills |*hostname| with the result.
Jason Monk9fd69be2014-03-18 11:55:59 -0400214bool GetHostnameArgument(const v8::FunctionCallbackInfo<v8::Value>& args, std::string* hostname) {
Jason Monkfc934182013-07-22 13:20:39 -0400215 // The first argument should be a string.
216 if (args.Length() == 0 || args[0].IsEmpty() || !args[0]->IsString())
217 return false;
218
Jason Monkf5cf6e32013-07-23 17:26:23 -0400219 const android::String16 hostname_utf16 = V8StringToUTF16(args[0]->ToString());
Jason Monkfc934182013-07-22 13:20:39 -0400220
221 // If the hostname is already in ASCII, simply return it as is.
222 if (IsStringASCII(hostname_utf16)) {
223 *hostname = UTF16ToASCII(hostname_utf16);
224 return true;
225 }
226 return false;
227}
228
229// Wrapper for passing around IP address strings and IPAddressNumber objects.
230struct IPAddress {
231 IPAddress(const std::string& ip_string, const IPAddressNumber& ip_number)
232 : string_value(ip_string),
233 ip_address_number(ip_number) {
234 }
235
236 // Used for sorting IP addresses in ascending order in SortIpAddressList().
237 // IP6 addresses are placed ahead of IPv4 addresses.
238 bool operator<(const IPAddress& rhs) const {
239 const IPAddressNumber& ip1 = this->ip_address_number;
240 const IPAddressNumber& ip2 = rhs.ip_address_number;
241 if (ip1.size() != ip2.size())
242 return ip1.size() > ip2.size(); // IPv6 before IPv4.
243 return memcmp(&ip1[0], &ip2[0], ip1.size()) < 0; // Ascending order.
244 }
245
246 std::string string_value;
247 IPAddressNumber ip_address_number;
248};
249
250template<typename STR>
251bool RemoveCharsT(const STR& input,
252 const typename STR::value_type remove_chars[],
253 STR* output) {
254 bool removed = false;
255 size_t found;
256
257 *output = input;
258
259 found = output->find_first_of(remove_chars);
260 while (found != STR::npos) {
261 removed = true;
262 output->replace(found, 1, STR());
263 found = output->find_first_of(remove_chars, found);
264 }
265
266 return removed;
267}
268
Jason Monkfc934182013-07-22 13:20:39 -0400269bool RemoveChars(const std::string& input,
270 const char remove_chars[],
271 std::string* output) {
272 return RemoveCharsT(input, remove_chars, output);
273}
274
275// Handler for "sortIpAddressList(IpAddressList)". |ip_address_list| is a
276// semi-colon delimited string containing IP addresses.
277// |sorted_ip_address_list| is the resulting list of sorted semi-colon delimited
278// IP addresses or an empty string if unable to sort the IP address list.
279// Returns 'true' if the sorting was successful, and 'false' if the input was an
280// empty string, a string of separators (";" in this case), or if any of the IP
281// addresses in the input list failed to parse.
282bool SortIpAddressList(const std::string& ip_address_list,
283 std::string* sorted_ip_address_list) {
284 sorted_ip_address_list->clear();
285
286 // Strip all whitespace (mimics IE behavior).
287 std::string cleaned_ip_address_list;
288 RemoveChars(ip_address_list, " \t", &cleaned_ip_address_list);
289 if (cleaned_ip_address_list.empty())
290 return false;
291
292 // Split-up IP addresses and store them in a vector.
293 std::vector<IPAddress> ip_vector;
294 IPAddressNumber ip_num;
295 char *tok_list = strtok((char *)cleaned_ip_address_list.c_str(), ";");
296 while (tok_list != NULL) {
297 if (!ParseIPLiteralToNumber(tok_list, &ip_num))
298 return false;
299 ip_vector.push_back(IPAddress(tok_list, ip_num));
Jason Monk86b75a52013-08-23 17:10:51 -0400300 tok_list = strtok(NULL, ";");
Jason Monkfc934182013-07-22 13:20:39 -0400301 }
302
303 if (ip_vector.empty()) // Can happen if we have something like
304 return false; // sortIpAddressList(";") or sortIpAddressList("; ;")
305
306 // Sort lists according to ascending numeric value.
307 if (ip_vector.size() > 1)
308 std::stable_sort(ip_vector.begin(), ip_vector.end());
309
310 // Return a semi-colon delimited list of sorted addresses (IPv6 followed by
311 // IPv4).
312 for (size_t i = 0; i < ip_vector.size(); ++i) {
313 if (i > 0)
314 *sorted_ip_address_list += ";";
315 *sorted_ip_address_list += ip_vector[i].string_value;
316 }
317 return true;
318}
319
320
321// Handler for "isInNetEx(ip_address, ip_prefix)". |ip_address| is a string
322// containing an IPv4/IPv6 address, and |ip_prefix| is a string containg a
323// slash-delimited IP prefix with the top 'n' bits specified in the bit
324// field. This returns 'true' if the address is in the same subnet, and
325// 'false' otherwise. Also returns 'false' if the prefix is in an incorrect
326// format, or if an address and prefix of different types are used (e.g. IPv6
327// address and IPv4 prefix).
328bool IsInNetEx(const std::string& ip_address, const std::string& ip_prefix) {
329 IPAddressNumber address;
Jason Monkeafc0fa2013-08-23 17:05:52 -0400330 std::string cleaned_ip_address;
331 if (RemoveChars(ip_address, " \t", &cleaned_ip_address))
332 return false;
Jason Monkfc934182013-07-22 13:20:39 -0400333 if (!ParseIPLiteralToNumber(ip_address, &address))
334 return false;
335
336 IPAddressNumber prefix;
337 size_t prefix_length_in_bits;
338 if (!ParseCIDRBlock(ip_prefix, &prefix, &prefix_length_in_bits))
339 return false;
340
341 // Both |address| and |prefix| must be of the same type (IPv4 or IPv6).
342 if (address.size() != prefix.size())
343 return false;
344
345 return IPNumberMatchesPrefix(address, prefix, prefix_length_in_bits);
346}
347
348} // namespace
349
350// ProxyResolverV8::Context ---------------------------------------------------
351
352class ProxyResolverV8::Context {
353 public:
Jason Monkf5cf6e32013-07-23 17:26:23 -0400354 explicit Context(ProxyResolverJSBindings* js_bindings,
Jason Monk9fd69be2014-03-18 11:55:59 -0400355 ProxyErrorListener* error_listener, v8::Isolate* isolate)
356 : js_bindings_(js_bindings), error_listener_(error_listener), isolate_(isolate) {
Jason Monkfc934182013-07-22 13:20:39 -0400357 }
358
359 ~Context() {
Jason Monk9fd69be2014-03-18 11:55:59 -0400360 v8::Locker locked(isolate_);
361 v8::Isolate::Scope isolate_scope(isolate_);
Jason Monkfc934182013-07-22 13:20:39 -0400362
Jason Monk9fd69be2014-03-18 11:55:59 -0400363 v8_this_.Reset();
364 v8_context_.Reset();
Jason Monkfc934182013-07-22 13:20:39 -0400365 }
366
Jason Monk40adcb52013-08-23 17:19:31 -0400367 int ResolveProxy(const android::String16 url, const android::String16 host,
368 android::String16* results) {
Jason Monk9fd69be2014-03-18 11:55:59 -0400369 v8::Locker locked(isolate_);
370 v8::Isolate::Scope isolate_scope(isolate_);
371 v8::HandleScope scope(isolate_);
Jason Monkfc934182013-07-22 13:20:39 -0400372
Jason Monk9fd69be2014-03-18 11:55:59 -0400373 v8::Local<v8::Context> context =
374 v8::Local<v8::Context>::New(isolate_, v8_context_);
375 v8::Context::Scope function_scope(context);
Jason Monkfc934182013-07-22 13:20:39 -0400376
377 v8::Local<v8::Value> function;
378 if (!GetFindProxyForURL(&function)) {
Jason Monk40adcb52013-08-23 17:19:31 -0400379 error_listener_->ErrorMessage(
380 android::String16("FindProxyForURL() is undefined"));
Jason Monkfc934182013-07-22 13:20:39 -0400381 return ERR_PAC_SCRIPT_FAILED;
382 }
383
384 v8::Handle<v8::Value> argv[] = {
Jason Monk9fd69be2014-03-18 11:55:59 -0400385 UTF16StringToV8String(isolate_, url),
386 UTF16StringToV8String(isolate_, host) };
Jason Monkfc934182013-07-22 13:20:39 -0400387
388 v8::TryCatch try_catch;
389 v8::Local<v8::Value> ret = v8::Function::Cast(*function)->Call(
Jason Monk9fd69be2014-03-18 11:55:59 -0400390 context->Global(), 2, argv);
Jason Monkfc934182013-07-22 13:20:39 -0400391
392 if (try_catch.HasCaught()) {
Jason Monk40adcb52013-08-23 17:19:31 -0400393 error_listener_->ErrorMessage(
394 V8StringToUTF16(try_catch.Message()->Get()));
Jason Monkfc934182013-07-22 13:20:39 -0400395 return ERR_PAC_SCRIPT_FAILED;
396 }
397
398 if (!ret->IsString()) {
Jason Monk40adcb52013-08-23 17:19:31 -0400399 error_listener_->ErrorMessage(
400 android::String16("FindProxyForURL() did not return a string."));
Jason Monkfc934182013-07-22 13:20:39 -0400401 return ERR_PAC_SCRIPT_FAILED;
402 }
403
Jason Monkf5cf6e32013-07-23 17:26:23 -0400404 *results = V8StringToUTF16(ret->ToString());
Jason Monkfc934182013-07-22 13:20:39 -0400405
Jason Monkf5cf6e32013-07-23 17:26:23 -0400406 if (!IsStringASCII(*results)) {
Jason Monkfc934182013-07-22 13:20:39 -0400407 // TODO: Rather than failing when a wide string is returned, we
408 // could extend the parsing to handle IDNA hostnames by
409 // converting them to ASCII punycode.
410 // crbug.com/47234
Jason Monk40adcb52013-08-23 17:19:31 -0400411 error_listener_->ErrorMessage(
412 android::String16("FindProxyForURL() returned a non-ASCII string"));
Jason Monkfc934182013-07-22 13:20:39 -0400413 return ERR_PAC_SCRIPT_FAILED;
414 }
415
Jason Monkfc934182013-07-22 13:20:39 -0400416 return OK;
417 }
418
Jason Monkf5cf6e32013-07-23 17:26:23 -0400419 int InitV8(const android::String16& pac_script) {
Jason Monk9fd69be2014-03-18 11:55:59 -0400420 v8::Locker locked(isolate_);
421 v8::Isolate::Scope isolate_scope(isolate_);
422 v8::HandleScope scope(isolate_);
Jason Monkfc934182013-07-22 13:20:39 -0400423
Jason Monk9fd69be2014-03-18 11:55:59 -0400424 v8_this_.Reset(isolate_, v8::External::New(isolate_, this));
425 v8::Local<v8::External> v8_this =
426 v8::Local<v8::External>::New(isolate_, v8_this_);
Jason Monkfc934182013-07-22 13:20:39 -0400427 v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
428
429 // Attach the javascript bindings.
430 v8::Local<v8::FunctionTemplate> alert_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400431 v8::FunctionTemplate::New(isolate_, &AlertCallback, v8_this);
432 global_template->Set(ASCIILiteralToV8String(isolate_, "alert"), alert_template);
Jason Monkfc934182013-07-22 13:20:39 -0400433
434 v8::Local<v8::FunctionTemplate> my_ip_address_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400435 v8::FunctionTemplate::New(isolate_, &MyIpAddressCallback, v8_this);
436 global_template->Set(ASCIILiteralToV8String(isolate_, "myIpAddress"),
Jason Monkfc934182013-07-22 13:20:39 -0400437 my_ip_address_template);
438
439 v8::Local<v8::FunctionTemplate> dns_resolve_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400440 v8::FunctionTemplate::New(isolate_, &DnsResolveCallback, v8_this);
441 global_template->Set(ASCIILiteralToV8String(isolate_, "dnsResolve"),
Jason Monkfc934182013-07-22 13:20:39 -0400442 dns_resolve_template);
443
444 // Microsoft's PAC extensions:
445
446 v8::Local<v8::FunctionTemplate> dns_resolve_ex_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400447 v8::FunctionTemplate::New(isolate_, &DnsResolveExCallback, v8_this);
448 global_template->Set(ASCIILiteralToV8String(isolate_, "dnsResolveEx"),
Jason Monkfc934182013-07-22 13:20:39 -0400449 dns_resolve_ex_template);
450
451 v8::Local<v8::FunctionTemplate> my_ip_address_ex_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400452 v8::FunctionTemplate::New(isolate_, &MyIpAddressExCallback, v8_this);
453 global_template->Set(ASCIILiteralToV8String(isolate_, "myIpAddressEx"),
Jason Monkfc934182013-07-22 13:20:39 -0400454 my_ip_address_ex_template);
455
456 v8::Local<v8::FunctionTemplate> sort_ip_address_list_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400457 v8::FunctionTemplate::New(isolate_, &SortIpAddressListCallback, v8_this);
458 global_template->Set(ASCIILiteralToV8String(isolate_, "sortIpAddressList"),
Jason Monkfc934182013-07-22 13:20:39 -0400459 sort_ip_address_list_template);
460
461 v8::Local<v8::FunctionTemplate> is_in_net_ex_template =
Jason Monk9fd69be2014-03-18 11:55:59 -0400462 v8::FunctionTemplate::New(isolate_, &IsInNetExCallback, v8_this);
463 global_template->Set(ASCIILiteralToV8String(isolate_, "isInNetEx"),
Jason Monkfc934182013-07-22 13:20:39 -0400464 is_in_net_ex_template);
465
Jason Monk9fd69be2014-03-18 11:55:59 -0400466 v8_context_.Reset(
467 isolate_, v8::Context::New(isolate_, NULL, global_template));
Jason Monkfc934182013-07-22 13:20:39 -0400468
Jason Monk9fd69be2014-03-18 11:55:59 -0400469 v8::Local<v8::Context> context =
470 v8::Local<v8::Context>::New(isolate_, v8_context_);
471 v8::Context::Scope ctx(context);
Jason Monkfc934182013-07-22 13:20:39 -0400472
473 // Add the PAC utility functions to the environment.
474 // (This script should never fail, as it is a string literal!)
475 // Note that the two string literals are concatenated.
476 int rv = RunScript(
Jason Monk9fd69be2014-03-18 11:55:59 -0400477 ASCIILiteralToV8String(isolate_,
Jason Monkfc934182013-07-22 13:20:39 -0400478 PROXY_RESOLVER_SCRIPT
479 PROXY_RESOLVER_SCRIPT_EX),
480 kPacUtilityResourceName);
481 if (rv != OK) {
482 return rv;
483 }
484
485 // Add the user's PAC code to the environment.
Jason Monk9fd69be2014-03-18 11:55:59 -0400486 rv = RunScript(UTF16StringToV8String(isolate_, pac_script), kPacResourceName);
Jason Monkfc934182013-07-22 13:20:39 -0400487 if (rv != OK) {
488 return rv;
489 }
490
491 // At a minimum, the FindProxyForURL() function must be defined for this
492 // to be a legitimiate PAC script.
493 v8::Local<v8::Value> function;
494 if (!GetFindProxyForURL(&function))
495 return ERR_PAC_SCRIPT_FAILED;
496
497 return OK;
498 }
499
500 void PurgeMemory() {
Jason Monk9fd69be2014-03-18 11:55:59 -0400501 v8::Locker locked(isolate_);
502 v8::Isolate::Scope isolate_scope(isolate_);
Ben Murdoche80b5fa2014-07-31 16:47:35 +0100503 isolate_->LowMemoryNotification();
Jason Monkfc934182013-07-22 13:20:39 -0400504 }
505
506 private:
507 bool GetFindProxyForURL(v8::Local<v8::Value>* function) {
Jason Monk9fd69be2014-03-18 11:55:59 -0400508 v8::Local<v8::Context> context =
509 v8::Local<v8::Context>::New(isolate_, v8_context_);
510 *function = context->Global()->Get(
511 ASCIILiteralToV8String(isolate_, "FindProxyForURL"));
Jason Monkfc934182013-07-22 13:20:39 -0400512 return (*function)->IsFunction();
513 }
514
515 // Handle an exception thrown by V8.
516 void HandleError(v8::Handle<v8::Message> message) {
517 if (message.IsEmpty())
518 return;
Jason Monkf5cf6e32013-07-23 17:26:23 -0400519 error_listener_->ErrorMessage(V8StringToUTF16(message->Get()));
Jason Monkfc934182013-07-22 13:20:39 -0400520 }
521
522 // Compiles and runs |script| in the current V8 context.
523 // Returns OK on success, otherwise an error code.
524 int RunScript(v8::Handle<v8::String> script, const char* script_name) {
525 v8::TryCatch try_catch;
526
527 // Compile the script.
528 v8::ScriptOrigin origin =
Jason Monk9fd69be2014-03-18 11:55:59 -0400529 v8::ScriptOrigin(ASCIILiteralToV8String(isolate_, script_name));
Jason Monkfc934182013-07-22 13:20:39 -0400530 v8::Local<v8::Script> code = v8::Script::Compile(script, &origin);
531
532 // Execute.
533 if (!code.IsEmpty())
534 code->Run();
535
536 // Check for errors.
537 if (try_catch.HasCaught()) {
538 HandleError(try_catch.Message());
539 return ERR_PAC_SCRIPT_FAILED;
540 }
541
542 return OK;
543 }
544
545 // V8 callback for when "alert()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400546 static void AlertCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400547 Context* context =
548 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
549
550 // Like firefox we assume "undefined" if no argument was specified, and
551 // disregard any arguments beyond the first.
Jason Monkf5cf6e32013-07-23 17:26:23 -0400552 android::String16 message;
Jason Monkfc934182013-07-22 13:20:39 -0400553 if (args.Length() == 0) {
554 std::string undef = "undefined";
Jason Monkf5cf6e32013-07-23 17:26:23 -0400555 android::String8 undef8(undef.c_str());
556 android::String16 wundef(undef8);
Jason Monkfc934182013-07-22 13:20:39 -0400557 message = wundef;
558 } else {
Jason Monk9fd69be2014-03-18 11:55:59 -0400559 if (!V8ObjectToUTF16String(args[0], &message, args.GetIsolate()))
560 return; // toString() threw an exception.
Jason Monkfc934182013-07-22 13:20:39 -0400561 }
562
Jason Monkf5cf6e32013-07-23 17:26:23 -0400563 context->error_listener_->AlertMessage(message);
Jason Monk9fd69be2014-03-18 11:55:59 -0400564 return;
Jason Monkfc934182013-07-22 13:20:39 -0400565 }
566
567 // V8 callback for when "myIpAddress()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400568 static void MyIpAddressCallback(
569 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400570 Context* context =
571 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
572
573 std::string result;
574 bool success;
575
576 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400577 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400578
579 // We shouldn't be called with any arguments, but will not complain if
580 // we are.
581 success = context->js_bindings_->MyIpAddress(&result);
582 }
583
Jason Monk9fd69be2014-03-18 11:55:59 -0400584 if (!success) {
585 args.GetReturnValue().Set(ASCIILiteralToV8String(args.GetIsolate(), "127.0.0.1"));
586 } else {
587 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), result));
588 }
Jason Monkfc934182013-07-22 13:20:39 -0400589 }
590
591 // V8 callback for when "myIpAddressEx()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400592 static void MyIpAddressExCallback(
593 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400594 Context* context =
595 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
596
597 std::string ip_address_list;
598 bool success;
599
600 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400601 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400602
603 // We shouldn't be called with any arguments, but will not complain if
604 // we are.
605 success = context->js_bindings_->MyIpAddressEx(&ip_address_list);
606 }
607
608 if (!success)
609 ip_address_list = std::string();
Jason Monk9fd69be2014-03-18 11:55:59 -0400610 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), ip_address_list));
Jason Monkfc934182013-07-22 13:20:39 -0400611 }
612
613 // V8 callback for when "dnsResolve()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400614 static void DnsResolveCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400615 Context* context =
616 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
617
618 // We need at least one string argument.
619 std::string hostname;
Jason Monk9fd69be2014-03-18 11:55:59 -0400620 if (!GetHostnameArgument(args, &hostname)) {
621 return;
622 }
Jason Monkfc934182013-07-22 13:20:39 -0400623
624 std::string ip_address;
625 bool success;
626
627 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400628 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400629 success = context->js_bindings_->DnsResolve(hostname, &ip_address);
630 }
631
Jason Monk9fd69be2014-03-18 11:55:59 -0400632 if (success) {
633 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), ip_address));
634 } else {
635 args.GetReturnValue().SetNull();
636 }
Jason Monkfc934182013-07-22 13:20:39 -0400637 }
638
639 // V8 callback for when "dnsResolveEx()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400640 static void DnsResolveExCallback(
641 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400642 Context* context =
643 static_cast<Context*>(v8::External::Cast(*args.Data())->Value());
644
645 // We need at least one string argument.
646 std::string hostname;
Jason Monk9fd69be2014-03-18 11:55:59 -0400647 if (!GetHostnameArgument(args, &hostname)) {
648 args.GetReturnValue().SetNull();
649 return;
650 }
Jason Monkfc934182013-07-22 13:20:39 -0400651
652 std::string ip_address_list;
653 bool success;
654
655 {
Jason Monk9fd69be2014-03-18 11:55:59 -0400656 v8::Unlocker unlocker(args.GetIsolate());
Jason Monkfc934182013-07-22 13:20:39 -0400657 success = context->js_bindings_->DnsResolveEx(hostname, &ip_address_list);
658 }
659
660 if (!success)
661 ip_address_list = std::string();
662
Jason Monk9fd69be2014-03-18 11:55:59 -0400663 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), ip_address_list));
Jason Monkfc934182013-07-22 13:20:39 -0400664 }
665
666 // V8 callback for when "sortIpAddressList()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400667 static void SortIpAddressListCallback(
668 const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400669 // We need at least one string argument.
Jason Monk9fd69be2014-03-18 11:55:59 -0400670 if (args.Length() == 0 || args[0].IsEmpty() || !args[0]->IsString()) {
671 args.GetReturnValue().SetNull();
672 return;
673 }
Jason Monkfc934182013-07-22 13:20:39 -0400674
675 std::string ip_address_list = V8StringToUTF8(args[0]->ToString());
676 std::string sorted_ip_address_list;
677 bool success = SortIpAddressList(ip_address_list, &sorted_ip_address_list);
Jason Monk9fd69be2014-03-18 11:55:59 -0400678 if (!success) {
679 args.GetReturnValue().Set(false);
680 return;
681 }
682 args.GetReturnValue().Set(ASCIIStringToV8String(args.GetIsolate(), sorted_ip_address_list));
Jason Monkfc934182013-07-22 13:20:39 -0400683 }
684
685 // V8 callback for when "isInNetEx()" is invoked by the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400686 static void IsInNetExCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
Jason Monkfc934182013-07-22 13:20:39 -0400687 // We need at least 2 string arguments.
688 if (args.Length() < 2 || args[0].IsEmpty() || !args[0]->IsString() ||
Jason Monk9fd69be2014-03-18 11:55:59 -0400689 args[1].IsEmpty() || !args[1]->IsString()) {
690 args.GetReturnValue().SetNull();
691 return;
692 }
Jason Monkfc934182013-07-22 13:20:39 -0400693
694 std::string ip_address = V8StringToUTF8(args[0]->ToString());
695 std::string ip_prefix = V8StringToUTF8(args[1]->ToString());
Jason Monk9fd69be2014-03-18 11:55:59 -0400696 args.GetReturnValue().Set(IsInNetEx(ip_address, ip_prefix));
Jason Monkfc934182013-07-22 13:20:39 -0400697 }
698
699 ProxyResolverJSBindings* js_bindings_;
Jason Monkf5cf6e32013-07-23 17:26:23 -0400700 ProxyErrorListener* error_listener_;
Jason Monk9fd69be2014-03-18 11:55:59 -0400701 v8::Isolate* isolate_;
Jason Monkfc934182013-07-22 13:20:39 -0400702 v8::Persistent<v8::External> v8_this_;
703 v8::Persistent<v8::Context> v8_context_;
704};
705
706// ProxyResolverV8 ------------------------------------------------------------
707
708ProxyResolverV8::ProxyResolverV8(
Jason Monkf5cf6e32013-07-23 17:26:23 -0400709 ProxyResolverJSBindings* custom_js_bindings,
710 ProxyErrorListener* error_listener)
711 : context_(NULL), js_bindings_(custom_js_bindings),
712 error_listener_(error_listener) {
713
Jason Monkfc934182013-07-22 13:20:39 -0400714}
715
716ProxyResolverV8::~ProxyResolverV8() {
Jason Monkc06a8d62013-08-19 10:36:23 -0400717 if (context_ != NULL) {
718 delete context_;
719 context_ = NULL;
720 }
721 if (js_bindings_ != NULL) {
722 delete js_bindings_;
723 }
Jason Monkfc934182013-07-22 13:20:39 -0400724}
725
Jason Monkf5cf6e32013-07-23 17:26:23 -0400726int ProxyResolverV8::GetProxyForURL(const android::String16 spec, const android::String16 host,
727 android::String16* results) {
Jason Monkfc934182013-07-22 13:20:39 -0400728 // If the V8 instance has not been initialized (either because
729 // SetPacScript() wasn't called yet, or because it failed.
730 if (context_ == NULL)
731 return ERR_FAILED;
732
733 // Otherwise call into V8.
734 int rv = context_->ResolveProxy(spec, host, results);
735
736 return rv;
737}
738
Jason Monkfc934182013-07-22 13:20:39 -0400739void ProxyResolverV8::PurgeMemory() {
740 context_->PurgeMemory();
741}
742
Jason Monk40adcb52013-08-23 17:19:31 -0400743int ProxyResolverV8::SetPacScript(const android::String16& script_data) {
Jason Monkfc934182013-07-22 13:20:39 -0400744 if (context_ != NULL) {
745 delete context_;
Jason Monkc06a8d62013-08-19 10:36:23 -0400746 context_ = NULL;
Jason Monkfc934182013-07-22 13:20:39 -0400747 }
Jason Monkf5cf6e32013-07-23 17:26:23 -0400748 if (script_data.size() == 0)
Jason Monkfc934182013-07-22 13:20:39 -0400749 return ERR_PAC_SCRIPT_FAILED;
750
751 // Try parsing the PAC script.
Jason Monk9fd69be2014-03-18 11:55:59 -0400752 context_ = new Context(js_bindings_, error_listener_, v8::Isolate::New());
Jason Monkfc934182013-07-22 13:20:39 -0400753 int rv;
754 if ((rv = context_->InitV8(script_data)) != OK) {
755 context_ = NULL;
756 }
757 if (rv != OK)
758 context_ = NULL;
759 return rv;
760}
761
762} // namespace net