1 // Copyright (c) 2012 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.
5 #include "net/proxy/proxy_resolver_v8.h"
10 #include "base/basictypes.h"
11 #include "base/compiler_specific.h"
12 #include "base/debug/leak_annotations.h"
13 #include "base/logging.h"
14 #include "base/strings/string_tokenizer.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/synchronization/lock.h"
18 #include "gin/array_buffer.h"
19 #include "gin/public/isolate_holder.h"
20 #include "net/base/net_errors.h"
21 #include "net/base/net_log.h"
22 #include "net/base/net_util.h"
23 #include "net/proxy/proxy_info.h"
24 #include "net/proxy/proxy_resolver_script.h"
26 #include "url/url_canon.h"
27 #include "v8/include/v8.h"
29 // Notes on the javascript environment:
31 // For the majority of the PAC utility functions, we use the same code
32 // as Firefox. See the javascript library that proxy_resolver_scipt.h
35 // In addition, we implement a subset of Microsoft's extensions to PAC.
40 // - sortIpAddressList()
42 // It is worth noting that the original PAC specification does not describe
43 // the return values on failure. Consequently, there are compatibility
44 // differences between browsers on what to return on failure, which are
47 // --------------------+-------------+-------------------+--------------
48 // | Firefox3 | InternetExplorer8 | --> Us <---
49 // --------------------+-------------+-------------------+--------------
50 // myIpAddress() | "127.0.0.1" | ??? | "127.0.0.1"
51 // dnsResolve() | null | false | null
52 // myIpAddressEx() | N/A | "" | ""
53 // sortIpAddressList() | N/A | false | false
54 // dnsResolveEx() | N/A | "" | ""
55 // isInNetEx() | N/A | false | false
56 // --------------------+-------------+-------------------+--------------
58 // TODO(eroman): The cell above reading ??? means I didn't test it.
60 // Another difference is in how dnsResolve() and myIpAddress() are
61 // implemented -- whether they should restrict to IPv4 results, or
62 // include both IPv4 and IPv6. The following table illustrates the
65 // --------------------+-------------+-------------------+--------------
66 // | Firefox3 | InternetExplorer8 | --> Us <---
67 // --------------------+-------------+-------------------+--------------
68 // myIpAddress() | IPv4/IPv6 | IPv4 | IPv4
69 // dnsResolve() | IPv4/IPv6 | IPv4 | IPv4
70 // isResolvable() | IPv4/IPv6 | IPv4 | IPv4
71 // myIpAddressEx() | N/A | IPv4/IPv6 | IPv4/IPv6
72 // dnsResolveEx() | N/A | IPv4/IPv6 | IPv4/IPv6
73 // sortIpAddressList() | N/A | IPv4/IPv6 | IPv4/IPv6
74 // isResolvableEx() | N/A | IPv4/IPv6 | IPv4/IPv6
75 // isInNetEx() | N/A | IPv4/IPv6 | IPv4/IPv6
76 // -----------------+-------------+-------------------+--------------
82 // Pseudo-name for the PAC script.
83 const char kPacResourceName
[] = "proxy-pac-script.js";
84 // Pseudo-name for the PAC utility script.
85 const char kPacUtilityResourceName
[] = "proxy-pac-utility-script.js";
87 // External string wrapper so V8 can access the UTF16 string wrapped by
88 // ProxyResolverScriptData.
89 class V8ExternalStringFromScriptData
90 : public v8::String::ExternalStringResource
{
92 explicit V8ExternalStringFromScriptData(
93 const scoped_refptr
<ProxyResolverScriptData
>& script_data
)
94 : script_data_(script_data
) {}
96 const uint16_t* data() const override
{
97 return reinterpret_cast<const uint16
*>(script_data_
->utf16().data());
100 size_t length() const override
{ return script_data_
->utf16().size(); }
103 const scoped_refptr
<ProxyResolverScriptData
> script_data_
;
104 DISALLOW_COPY_AND_ASSIGN(V8ExternalStringFromScriptData
);
107 // External string wrapper so V8 can access a string literal.
108 class V8ExternalASCIILiteral
109 : public v8::String::ExternalOneByteStringResource
{
111 // |ascii| must be a NULL-terminated C string, and must remain valid
112 // throughout this object's lifetime.
113 V8ExternalASCIILiteral(const char* ascii
, size_t length
)
114 : ascii_(ascii
), length_(length
) {
115 DCHECK(base::IsStringASCII(ascii
));
118 const char* data() const override
{ return ascii_
; }
120 size_t length() const override
{ return length_
; }
125 DISALLOW_COPY_AND_ASSIGN(V8ExternalASCIILiteral
);
128 // When creating a v8::String from a C++ string we have two choices: create
129 // a copy, or create a wrapper that shares the same underlying storage.
130 // For small strings it is better to just make a copy, whereas for large
131 // strings there are savings by sharing the storage. This number identifies
132 // the cutoff length for when to start wrapping rather than creating copies.
133 const size_t kMaxStringBytesForCopy
= 256;
135 // Converts a V8 String to a UTF8 std::string.
136 std::string
V8StringToUTF8(v8::Local
<v8::String
> s
) {
137 int len
= s
->Length();
140 s
->WriteUtf8(WriteInto(&result
, len
+ 1));
144 // Converts a V8 String to a UTF16 base::string16.
145 base::string16
V8StringToUTF16(v8::Local
<v8::String
> s
) {
146 int len
= s
->Length();
147 base::string16 result
;
148 // Note that the reinterpret cast is because on Windows string16 is an alias
149 // to wstring, and hence has character type wchar_t not uint16_t.
151 s
->Write(reinterpret_cast<uint16_t*>(WriteInto(&result
, len
+ 1)), 0, len
);
155 // Converts an ASCII std::string to a V8 string.
156 v8::Local
<v8::String
> ASCIIStringToV8String(v8::Isolate
* isolate
,
157 const std::string
& s
) {
158 DCHECK(base::IsStringASCII(s
));
159 return v8::String::NewFromUtf8(isolate
, s
.data(), v8::String::kNormalString
,
163 // Converts a UTF16 base::string16 (warpped by a ProxyResolverScriptData) to a
165 v8::Local
<v8::String
> ScriptDataToV8String(
166 v8::Isolate
* isolate
, const scoped_refptr
<ProxyResolverScriptData
>& s
) {
167 if (s
->utf16().size() * 2 <= kMaxStringBytesForCopy
) {
168 return v8::String::NewFromTwoByte(
170 reinterpret_cast<const uint16_t*>(s
->utf16().data()),
171 v8::String::kNormalString
,
174 return v8::String::NewExternal(isolate
,
175 new V8ExternalStringFromScriptData(s
));
178 // Converts an ASCII string literal to a V8 string.
179 v8::Local
<v8::String
> ASCIILiteralToV8String(v8::Isolate
* isolate
,
181 DCHECK(base::IsStringASCII(ascii
));
182 size_t length
= strlen(ascii
);
183 if (length
<= kMaxStringBytesForCopy
)
184 return v8::String::NewFromUtf8(isolate
, ascii
, v8::String::kNormalString
,
186 return v8::String::NewExternal(isolate
,
187 new V8ExternalASCIILiteral(ascii
, length
));
190 // Stringizes a V8 object by calling its toString() method. Returns true
191 // on success. This may fail if the toString() throws an exception.
192 bool V8ObjectToUTF16String(v8::Local
<v8::Value
> object
,
193 base::string16
* utf16_result
,
194 v8::Isolate
* isolate
) {
195 if (object
.IsEmpty())
198 v8::HandleScope
scope(isolate
);
199 v8::Local
<v8::String
> str_object
= object
->ToString(isolate
);
200 if (str_object
.IsEmpty())
202 *utf16_result
= V8StringToUTF16(str_object
);
206 // Extracts an hostname argument from |args|. On success returns true
207 // and fills |*hostname| with the result.
208 bool GetHostnameArgument(const v8::FunctionCallbackInfo
<v8::Value
>& args
,
209 std::string
* hostname
) {
210 // The first argument should be a string.
211 if (args
.Length() == 0 || args
[0].IsEmpty() || !args
[0]->IsString())
214 const base::string16 hostname_utf16
=
215 V8StringToUTF16(v8::Local
<v8::String
>::Cast(args
[0]));
217 // If the hostname is already in ASCII, simply return it as is.
218 if (base::IsStringASCII(hostname_utf16
)) {
219 *hostname
= base::UTF16ToASCII(hostname_utf16
);
223 // Otherwise try to convert it from IDN to punycode.
224 const int kInitialBufferSize
= 256;
225 url::RawCanonOutputT
<base::char16
, kInitialBufferSize
> punycode_output
;
226 if (!url::IDNToASCII(hostname_utf16
.data(), hostname_utf16
.length(),
231 // |punycode_output| should now be ASCII; convert it to a std::string.
232 // (We could use UTF16ToASCII() instead, but that requires an extra string
233 // copy. Since ASCII is a subset of UTF8 the following is equivalent).
234 bool success
= base::UTF16ToUTF8(punycode_output
.data(),
235 punycode_output
.length(),
238 DCHECK(base::IsStringASCII(*hostname
));
242 // Wrapper for passing around IP address strings and IPAddressNumber objects.
244 IPAddress(const std::string
& ip_string
, const IPAddressNumber
& ip_number
)
245 : string_value(ip_string
),
246 ip_address_number(ip_number
) {
249 // Used for sorting IP addresses in ascending order in SortIpAddressList().
250 // IP6 addresses are placed ahead of IPv4 addresses.
251 bool operator<(const IPAddress
& rhs
) const {
252 const IPAddressNumber
& ip1
= this->ip_address_number
;
253 const IPAddressNumber
& ip2
= rhs
.ip_address_number
;
254 if (ip1
.size() != ip2
.size())
255 return ip1
.size() > ip2
.size(); // IPv6 before IPv4.
256 DCHECK(ip1
.size() == ip2
.size());
257 return memcmp(&ip1
[0], &ip2
[0], ip1
.size()) < 0; // Ascending order.
260 std::string string_value
;
261 IPAddressNumber ip_address_number
;
264 // Handler for "sortIpAddressList(IpAddressList)". |ip_address_list| is a
265 // semi-colon delimited string containing IP addresses.
266 // |sorted_ip_address_list| is the resulting list of sorted semi-colon delimited
267 // IP addresses or an empty string if unable to sort the IP address list.
268 // Returns 'true' if the sorting was successful, and 'false' if the input was an
269 // empty string, a string of separators (";" in this case), or if any of the IP
270 // addresses in the input list failed to parse.
271 bool SortIpAddressList(const std::string
& ip_address_list
,
272 std::string
* sorted_ip_address_list
) {
273 sorted_ip_address_list
->clear();
275 // Strip all whitespace (mimics IE behavior).
276 std::string cleaned_ip_address_list
;
277 base::RemoveChars(ip_address_list
, " \t", &cleaned_ip_address_list
);
278 if (cleaned_ip_address_list
.empty())
281 // Split-up IP addresses and store them in a vector.
282 std::vector
<IPAddress
> ip_vector
;
283 IPAddressNumber ip_num
;
284 base::StringTokenizer
str_tok(cleaned_ip_address_list
, ";");
285 while (str_tok
.GetNext()) {
286 if (!ParseIPLiteralToNumber(str_tok
.token(), &ip_num
))
288 ip_vector
.push_back(IPAddress(str_tok
.token(), ip_num
));
291 if (ip_vector
.empty()) // Can happen if we have something like
292 return false; // sortIpAddressList(";") or sortIpAddressList("; ;")
294 DCHECK(!ip_vector
.empty());
296 // Sort lists according to ascending numeric value.
297 if (ip_vector
.size() > 1)
298 std::stable_sort(ip_vector
.begin(), ip_vector
.end());
300 // Return a semi-colon delimited list of sorted addresses (IPv6 followed by
302 for (size_t i
= 0; i
< ip_vector
.size(); ++i
) {
304 *sorted_ip_address_list
+= ";";
305 *sorted_ip_address_list
+= ip_vector
[i
].string_value
;
310 // Handler for "isInNetEx(ip_address, ip_prefix)". |ip_address| is a string
311 // containing an IPv4/IPv6 address, and |ip_prefix| is a string containg a
312 // slash-delimited IP prefix with the top 'n' bits specified in the bit
313 // field. This returns 'true' if the address is in the same subnet, and
314 // 'false' otherwise. Also returns 'false' if the prefix is in an incorrect
315 // format, or if an address and prefix of different types are used (e.g. IPv6
316 // address and IPv4 prefix).
317 bool IsInNetEx(const std::string
& ip_address
, const std::string
& ip_prefix
) {
318 IPAddressNumber address
;
319 if (!ParseIPLiteralToNumber(ip_address
, &address
))
322 IPAddressNumber prefix
;
323 size_t prefix_length_in_bits
;
324 if (!ParseCIDRBlock(ip_prefix
, &prefix
, &prefix_length_in_bits
))
327 // Both |address| and |prefix| must be of the same type (IPv4 or IPv6).
328 if (address
.size() != prefix
.size())
331 DCHECK((address
.size() == 4 && prefix
.size() == 4) ||
332 (address
.size() == 16 && prefix
.size() == 16));
334 return IPNumberMatchesPrefix(address
, prefix
, prefix_length_in_bits
);
339 // ProxyResolverV8::Context ---------------------------------------------------
341 class ProxyResolverV8::Context
{
343 Context(ProxyResolverV8
* parent
, v8::Isolate
* isolate
)
350 v8::Locker
locked(isolate_
);
351 v8::Isolate::Scope
isolate_scope(isolate_
);
357 JSBindings
* js_bindings() {
358 return parent_
->js_bindings_
;
361 int ResolveProxy(const GURL
& query_url
, ProxyInfo
* results
) {
362 v8::Locker
locked(isolate_
);
363 v8::Isolate::Scope
isolate_scope(isolate_
);
364 v8::HandleScope
scope(isolate_
);
366 v8::Local
<v8::Context
> context
=
367 v8::Local
<v8::Context
>::New(isolate_
, v8_context_
);
368 v8::Context::Scope
function_scope(context
);
370 v8::Local
<v8::Value
> function
;
371 if (!GetFindProxyForURL(&function
)) {
372 js_bindings()->OnError(
373 -1, base::ASCIIToUTF16("FindProxyForURL() is undefined."));
374 return ERR_PAC_SCRIPT_FAILED
;
377 v8::Local
<v8::Value
> argv
[] = {
378 ASCIIStringToV8String(isolate_
, query_url
.spec()),
379 ASCIIStringToV8String(isolate_
, query_url
.HostNoBrackets()),
382 v8::TryCatch try_catch
;
383 v8::Local
<v8::Value
> ret
= v8::Function::Cast(*function
)->Call(
384 context
->Global(), arraysize(argv
), argv
);
386 if (try_catch
.HasCaught()) {
387 HandleError(try_catch
.Message());
388 return ERR_PAC_SCRIPT_FAILED
;
391 if (!ret
->IsString()) {
392 js_bindings()->OnError(
393 -1, base::ASCIIToUTF16("FindProxyForURL() did not return a string."));
394 return ERR_PAC_SCRIPT_FAILED
;
397 base::string16 ret_str
= V8StringToUTF16(v8::Local
<v8::String
>::Cast(ret
));
399 if (!base::IsStringASCII(ret_str
)) {
400 // TODO(eroman): Rather than failing when a wide string is returned, we
401 // could extend the parsing to handle IDNA hostnames by
402 // converting them to ASCII punycode.
404 base::string16 error_message
=
405 base::ASCIIToUTF16("FindProxyForURL() returned a non-ASCII string "
406 "(crbug.com/47234): ") + ret_str
;
407 js_bindings()->OnError(-1, error_message
);
408 return ERR_PAC_SCRIPT_FAILED
;
411 results
->UsePacString(base::UTF16ToASCII(ret_str
));
415 int InitV8(const scoped_refptr
<ProxyResolverScriptData
>& pac_script
) {
416 v8::Locker
locked(isolate_
);
417 v8::Isolate::Scope
isolate_scope(isolate_
);
418 v8::HandleScope
scope(isolate_
);
420 v8_this_
.Reset(isolate_
, v8::External::New(isolate_
, this));
421 v8::Local
<v8::External
> v8_this
=
422 v8::Local
<v8::External
>::New(isolate_
, v8_this_
);
423 v8::Local
<v8::ObjectTemplate
> global_template
=
424 v8::ObjectTemplate::New(isolate_
);
426 // Attach the javascript bindings.
427 v8::Local
<v8::FunctionTemplate
> alert_template
=
428 v8::FunctionTemplate::New(isolate_
, &AlertCallback
, v8_this
);
429 global_template
->Set(ASCIILiteralToV8String(isolate_
, "alert"),
432 v8::Local
<v8::FunctionTemplate
> my_ip_address_template
=
433 v8::FunctionTemplate::New(isolate_
, &MyIpAddressCallback
, v8_this
);
434 global_template
->Set(ASCIILiteralToV8String(isolate_
, "myIpAddress"),
435 my_ip_address_template
);
437 v8::Local
<v8::FunctionTemplate
> dns_resolve_template
=
438 v8::FunctionTemplate::New(isolate_
, &DnsResolveCallback
, v8_this
);
439 global_template
->Set(ASCIILiteralToV8String(isolate_
, "dnsResolve"),
440 dns_resolve_template
);
442 // Microsoft's PAC extensions:
444 v8::Local
<v8::FunctionTemplate
> dns_resolve_ex_template
=
445 v8::FunctionTemplate::New(isolate_
, &DnsResolveExCallback
, v8_this
);
446 global_template
->Set(ASCIILiteralToV8String(isolate_
, "dnsResolveEx"),
447 dns_resolve_ex_template
);
449 v8::Local
<v8::FunctionTemplate
> my_ip_address_ex_template
=
450 v8::FunctionTemplate::New(isolate_
, &MyIpAddressExCallback
, v8_this
);
451 global_template
->Set(ASCIILiteralToV8String(isolate_
, "myIpAddressEx"),
452 my_ip_address_ex_template
);
454 v8::Local
<v8::FunctionTemplate
> sort_ip_address_list_template
=
455 v8::FunctionTemplate::New(isolate_
,
456 &SortIpAddressListCallback
,
458 global_template
->Set(ASCIILiteralToV8String(isolate_
, "sortIpAddressList"),
459 sort_ip_address_list_template
);
461 v8::Local
<v8::FunctionTemplate
> is_in_net_ex_template
=
462 v8::FunctionTemplate::New(isolate_
, &IsInNetExCallback
, v8_this
);
463 global_template
->Set(ASCIILiteralToV8String(isolate_
, "isInNetEx"),
464 is_in_net_ex_template
);
467 isolate_
, v8::Context::New(isolate_
, NULL
, global_template
));
469 v8::Local
<v8::Context
> context
=
470 v8::Local
<v8::Context
>::New(isolate_
, v8_context_
);
471 v8::Context::Scope
ctx(context
);
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.
477 ASCIILiteralToV8String(
479 PROXY_RESOLVER_SCRIPT
480 PROXY_RESOLVER_SCRIPT_EX
),
481 kPacUtilityResourceName
);
487 // Add the user's PAC code to the environment.
489 RunScript(ScriptDataToV8String(isolate_
, pac_script
), kPacResourceName
);
493 // At a minimum, the FindProxyForURL() function must be defined for this
494 // to be a legitimiate PAC script.
495 v8::Local
<v8::Value
> function
;
496 if (!GetFindProxyForURL(&function
)) {
497 js_bindings()->OnError(
498 -1, base::ASCIIToUTF16("FindProxyForURL() is undefined."));
499 return ERR_PAC_SCRIPT_FAILED
;
506 bool GetFindProxyForURL(v8::Local
<v8::Value
>* function
) {
507 v8::Local
<v8::Context
> context
=
508 v8::Local
<v8::Context
>::New(isolate_
, v8_context_
);
510 context
->Global()->Get(
511 ASCIILiteralToV8String(isolate_
, "FindProxyForURL"));
512 return (*function
)->IsFunction();
515 // Handle an exception thrown by V8.
516 void HandleError(v8::Local
<v8::Message
> message
) {
517 base::string16 error_message
;
518 int line_number
= -1;
520 if (!message
.IsEmpty()) {
521 line_number
= message
->GetLineNumber();
522 V8ObjectToUTF16String(message
->Get(), &error_message
, isolate_
);
525 js_bindings()->OnError(line_number
, error_message
);
528 // Compiles and runs |script| in the current V8 context.
529 // Returns OK on success, otherwise an error code.
530 int RunScript(v8::Local
<v8::String
> script
, const char* script_name
) {
531 v8::TryCatch try_catch
;
533 // Compile the script.
534 v8::ScriptOrigin origin
=
535 v8::ScriptOrigin(ASCIILiteralToV8String(isolate_
, script_name
));
536 v8::Local
<v8::Script
> code
= v8::Script::Compile(script
, &origin
);
543 if (try_catch
.HasCaught()) {
544 HandleError(try_catch
.Message());
545 return ERR_PAC_SCRIPT_FAILED
;
551 // V8 callback for when "alert()" is invoked by the PAC script.
552 static void AlertCallback(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
554 static_cast<Context
*>(v8::External::Cast(*args
.Data())->Value());
556 // Like firefox we assume "undefined" if no argument was specified, and
557 // disregard any arguments beyond the first.
558 base::string16 message
;
559 if (args
.Length() == 0) {
560 message
= base::ASCIIToUTF16("undefined");
562 if (!V8ObjectToUTF16String(args
[0], &message
, args
.GetIsolate()))
563 return; // toString() threw an exception.
566 context
->js_bindings()->Alert(message
);
569 // V8 callback for when "myIpAddress()" is invoked by the PAC script.
570 static void MyIpAddressCallback(
571 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
572 DnsResolveCallbackHelper(args
, JSBindings::MY_IP_ADDRESS
);
575 // V8 callback for when "myIpAddressEx()" is invoked by the PAC script.
576 static void MyIpAddressExCallback(
577 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
578 DnsResolveCallbackHelper(args
, JSBindings::MY_IP_ADDRESS_EX
);
581 // V8 callback for when "dnsResolve()" is invoked by the PAC script.
582 static void DnsResolveCallback(
583 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
584 DnsResolveCallbackHelper(args
, JSBindings::DNS_RESOLVE
);
587 // V8 callback for when "dnsResolveEx()" is invoked by the PAC script.
588 static void DnsResolveExCallback(
589 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
590 DnsResolveCallbackHelper(args
, JSBindings::DNS_RESOLVE_EX
);
593 // Shared code for implementing:
594 // - myIpAddress(), myIpAddressEx(), dnsResolve(), dnsResolveEx().
595 static void DnsResolveCallbackHelper(
596 const v8::FunctionCallbackInfo
<v8::Value
>& args
,
597 JSBindings::ResolveDnsOperation op
) {
599 static_cast<Context
*>(v8::External::Cast(*args
.Data())->Value());
601 std::string hostname
;
603 // dnsResolve() and dnsResolveEx() need at least 1 argument.
604 if (op
== JSBindings::DNS_RESOLVE
|| op
== JSBindings::DNS_RESOLVE_EX
) {
605 if (!GetHostnameArgument(args
, &hostname
)) {
606 if (op
== JSBindings::DNS_RESOLVE
)
607 args
.GetReturnValue().SetNull();
614 bool terminate
= false;
617 v8::Unlocker
unlocker(args
.GetIsolate());
618 success
= context
->js_bindings()->ResolveDns(
619 hostname
, op
, &result
, &terminate
);
623 v8::V8::TerminateExecution(args
.GetIsolate());
626 args
.GetReturnValue().Set(
627 ASCIIStringToV8String(args
.GetIsolate(), result
));
631 // Each function handles resolution errors differently.
633 case JSBindings::DNS_RESOLVE
:
634 args
.GetReturnValue().SetNull();
636 case JSBindings::DNS_RESOLVE_EX
:
637 args
.GetReturnValue().SetEmptyString();
639 case JSBindings::MY_IP_ADDRESS
:
640 args
.GetReturnValue().Set(
641 ASCIILiteralToV8String(args
.GetIsolate(), "127.0.0.1"));
643 case JSBindings::MY_IP_ADDRESS_EX
:
644 args
.GetReturnValue().SetEmptyString();
651 // V8 callback for when "sortIpAddressList()" is invoked by the PAC script.
652 static void SortIpAddressListCallback(
653 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
654 // We need at least one string argument.
655 if (args
.Length() == 0 || args
[0].IsEmpty() || !args
[0]->IsString()) {
656 args
.GetReturnValue().SetNull();
660 std::string ip_address_list
=
661 V8StringToUTF8(v8::Local
<v8::String
>::Cast(args
[0]));
662 if (!base::IsStringASCII(ip_address_list
)) {
663 args
.GetReturnValue().SetNull();
666 std::string sorted_ip_address_list
;
667 bool success
= SortIpAddressList(ip_address_list
, &sorted_ip_address_list
);
669 args
.GetReturnValue().Set(false);
672 args
.GetReturnValue().Set(
673 ASCIIStringToV8String(args
.GetIsolate(), sorted_ip_address_list
));
676 // V8 callback for when "isInNetEx()" is invoked by the PAC script.
677 static void IsInNetExCallback(
678 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
679 // We need at least 2 string arguments.
680 if (args
.Length() < 2 || args
[0].IsEmpty() || !args
[0]->IsString() ||
681 args
[1].IsEmpty() || !args
[1]->IsString()) {
682 args
.GetReturnValue().SetNull();
686 std::string ip_address
=
687 V8StringToUTF8(v8::Local
<v8::String
>::Cast(args
[0]));
688 if (!base::IsStringASCII(ip_address
)) {
689 args
.GetReturnValue().Set(false);
692 std::string ip_prefix
=
693 V8StringToUTF8(v8::Local
<v8::String
>::Cast(args
[1]));
694 if (!base::IsStringASCII(ip_prefix
)) {
695 args
.GetReturnValue().Set(false);
698 args
.GetReturnValue().Set(IsInNetEx(ip_address
, ip_prefix
));
701 mutable base::Lock lock_
;
702 ProxyResolverV8
* parent_
;
703 v8::Isolate
* isolate_
;
704 v8::Persistent
<v8::External
> v8_this_
;
705 v8::Persistent
<v8::Context
> v8_context_
;
708 // ProxyResolverV8 ------------------------------------------------------------
710 ProxyResolverV8::ProxyResolverV8()
711 : ProxyResolver(true /*expects_pac_bytes*/),
715 ProxyResolverV8::~ProxyResolverV8() {}
717 int ProxyResolverV8::GetProxyForURL(
718 const GURL
& query_url
, ProxyInfo
* results
,
719 const CompletionCallback
& /*callback*/,
720 RequestHandle
* /*request*/,
721 const BoundNetLog
& net_log
) {
722 DCHECK(js_bindings_
);
724 // If the V8 instance has not been initialized (either because
725 // SetPacScript() wasn't called yet, or because it failed.
729 // Otherwise call into V8.
730 int rv
= context_
->ResolveProxy(query_url
, results
);
735 void ProxyResolverV8::CancelRequest(RequestHandle request
) {
736 // This is a synchronous ProxyResolver; no possibility for async requests.
740 LoadState
ProxyResolverV8::GetLoadState(RequestHandle request
) const {
742 return LOAD_STATE_IDLE
;
745 void ProxyResolverV8::CancelSetPacScript() {
749 int ProxyResolverV8::SetPacScript(
750 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
751 const CompletionCallback
& /*callback*/) {
752 DCHECK(script_data
.get());
753 DCHECK(js_bindings_
);
756 if (script_data
->utf16().empty())
757 return ERR_PAC_SCRIPT_FAILED
;
759 // Try parsing the PAC script.
760 scoped_ptr
<Context
> context(new Context(this, GetDefaultIsolate()));
761 int rv
= context
->InitV8(script_data
);
763 context_
.reset(context
.release());
768 void ProxyResolverV8::EnsureIsolateCreated() {
769 if (g_proxy_resolver_isolate_
)
771 gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode
,
772 gin::ArrayBufferAllocator::SharedInstance());
773 g_proxy_resolver_isolate_
= new gin::IsolateHolder
;
774 ANNOTATE_LEAKING_OBJECT_PTR(g_proxy_resolver_isolate_
);
778 v8::Isolate
* ProxyResolverV8::GetDefaultIsolate() {
779 DCHECK(g_proxy_resolver_isolate_
)
780 << "Must call ProxyResolverV8::EnsureIsolateCreated() first";
781 return g_proxy_resolver_isolate_
->isolate();
784 gin::IsolateHolder
* ProxyResolverV8::g_proxy_resolver_isolate_
= NULL
;
787 size_t ProxyResolverV8::GetTotalHeapSize() {
788 if (!g_proxy_resolver_isolate_
)
791 v8::Locker
locked(g_proxy_resolver_isolate_
->isolate());
792 v8::Isolate::Scope
isolate_scope(g_proxy_resolver_isolate_
->isolate());
793 v8::HeapStatistics heap_statistics
;
794 g_proxy_resolver_isolate_
->isolate()->GetHeapStatistics(&heap_statistics
);
795 return heap_statistics
.total_heap_size();
799 size_t ProxyResolverV8::GetUsedHeapSize() {
800 if (!g_proxy_resolver_isolate_
)
803 v8::Locker
locked(g_proxy_resolver_isolate_
->isolate());
804 v8::Isolate::Scope
isolate_scope(g_proxy_resolver_isolate_
->isolate());
805 v8::HeapStatistics heap_statistics
;
806 g_proxy_resolver_isolate_
->isolate()->GetHeapStatistics(&heap_statistics
);
807 return heap_statistics
.used_heap_size();