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/logging.h"
13 #include "base/strings/string_tokenizer.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/synchronization/lock.h"
17 #include "net/base/net_errors.h"
18 #include "net/base/net_log.h"
19 #include "net/base/net_util.h"
20 #include "net/proxy/proxy_info.h"
21 #include "net/proxy/proxy_resolver_script.h"
23 #include "url/url_canon.h"
24 #include "v8/include/v8.h"
26 // Notes on the javascript environment:
28 // For the majority of the PAC utility functions, we use the same code
29 // as Firefox. See the javascript library that proxy_resolver_scipt.h
32 // In addition, we implement a subset of Microsoft's extensions to PAC.
37 // - sortIpAddressList()
39 // It is worth noting that the original PAC specification does not describe
40 // the return values on failure. Consequently, there are compatibility
41 // differences between browsers on what to return on failure, which are
44 // --------------------+-------------+-------------------+--------------
45 // | Firefox3 | InternetExplorer8 | --> Us <---
46 // --------------------+-------------+-------------------+--------------
47 // myIpAddress() | "127.0.0.1" | ??? | "127.0.0.1"
48 // dnsResolve() | null | false | null
49 // myIpAddressEx() | N/A | "" | ""
50 // sortIpAddressList() | N/A | false | false
51 // dnsResolveEx() | N/A | "" | ""
52 // isInNetEx() | N/A | false | false
53 // --------------------+-------------+-------------------+--------------
55 // TODO(eroman): The cell above reading ??? means I didn't test it.
57 // Another difference is in how dnsResolve() and myIpAddress() are
58 // implemented -- whether they should restrict to IPv4 results, or
59 // include both IPv4 and IPv6. The following table illustrates the
62 // --------------------+-------------+-------------------+--------------
63 // | Firefox3 | InternetExplorer8 | --> Us <---
64 // --------------------+-------------+-------------------+--------------
65 // myIpAddress() | IPv4/IPv6 | IPv4 | IPv4
66 // dnsResolve() | IPv4/IPv6 | IPv4 | IPv4
67 // isResolvable() | IPv4/IPv6 | IPv4 | IPv4
68 // myIpAddressEx() | N/A | IPv4/IPv6 | IPv4/IPv6
69 // dnsResolveEx() | N/A | IPv4/IPv6 | IPv4/IPv6
70 // sortIpAddressList() | N/A | IPv4/IPv6 | IPv4/IPv6
71 // isResolvableEx() | N/A | IPv4/IPv6 | IPv4/IPv6
72 // isInNetEx() | N/A | IPv4/IPv6 | IPv4/IPv6
73 // -----------------+-------------+-------------------+--------------
79 // Pseudo-name for the PAC script.
80 const char kPacResourceName
[] = "proxy-pac-script.js";
81 // Pseudo-name for the PAC utility script.
82 const char kPacUtilityResourceName
[] = "proxy-pac-utility-script.js";
84 // External string wrapper so V8 can access the UTF16 string wrapped by
85 // ProxyResolverScriptData.
86 class V8ExternalStringFromScriptData
87 : public v8::String::ExternalStringResource
{
89 explicit V8ExternalStringFromScriptData(
90 const scoped_refptr
<ProxyResolverScriptData
>& script_data
)
91 : script_data_(script_data
) {}
93 virtual const uint16_t* data() const OVERRIDE
{
94 return reinterpret_cast<const uint16
*>(script_data_
->utf16().data());
97 virtual size_t length() const OVERRIDE
{
98 return script_data_
->utf16().size();
102 const scoped_refptr
<ProxyResolverScriptData
> script_data_
;
103 DISALLOW_COPY_AND_ASSIGN(V8ExternalStringFromScriptData
);
106 // External string wrapper so V8 can access a string literal.
107 class V8ExternalASCIILiteral
: public v8::String::ExternalAsciiStringResource
{
109 // |ascii| must be a NULL-terminated C string, and must remain valid
110 // throughout this object's lifetime.
111 V8ExternalASCIILiteral(const char* ascii
, size_t length
)
112 : ascii_(ascii
), length_(length
) {
113 DCHECK(IsStringASCII(ascii
));
116 virtual const char* data() const OVERRIDE
{
120 virtual size_t length() const OVERRIDE
{
127 DISALLOW_COPY_AND_ASSIGN(V8ExternalASCIILiteral
);
130 // When creating a v8::String from a C++ string we have two choices: create
131 // a copy, or create a wrapper that shares the same underlying storage.
132 // For small strings it is better to just make a copy, whereas for large
133 // strings there are savings by sharing the storage. This number identifies
134 // the cutoff length for when to start wrapping rather than creating copies.
135 const size_t kMaxStringBytesForCopy
= 256;
137 // Converts a V8 String to a UTF8 std::string.
138 std::string
V8StringToUTF8(v8::Handle
<v8::String
> s
) {
139 int len
= s
->Length();
142 s
->WriteUtf8(WriteInto(&result
, len
+ 1));
146 // Converts a V8 String to a UTF16 base::string16.
147 base::string16
V8StringToUTF16(v8::Handle
<v8::String
> s
) {
148 int len
= s
->Length();
149 base::string16 result
;
150 // Note that the reinterpret cast is because on Windows string16 is an alias
151 // to wstring, and hence has character type wchar_t not uint16_t.
153 s
->Write(reinterpret_cast<uint16_t*>(WriteInto(&result
, len
+ 1)), 0, len
);
157 // Converts an ASCII std::string to a V8 string.
158 v8::Local
<v8::String
> ASCIIStringToV8String(v8::Isolate
* isolate
,
159 const std::string
& s
) {
160 DCHECK(IsStringASCII(s
));
161 return v8::String::NewFromUtf8(isolate
, s
.data(), v8::String::kNormalString
,
165 // Converts a UTF16 base::string16 (warpped by a ProxyResolverScriptData) to a
167 v8::Local
<v8::String
> ScriptDataToV8String(
168 v8::Isolate
* isolate
, const scoped_refptr
<ProxyResolverScriptData
>& s
) {
169 if (s
->utf16().size() * 2 <= kMaxStringBytesForCopy
) {
170 return v8::String::NewFromTwoByte(
172 reinterpret_cast<const uint16_t*>(s
->utf16().data()),
173 v8::String::kNormalString
,
176 return v8::String::NewExternal(isolate
,
177 new V8ExternalStringFromScriptData(s
));
180 // Converts an ASCII string literal to a V8 string.
181 v8::Local
<v8::String
> ASCIILiteralToV8String(v8::Isolate
* isolate
,
183 DCHECK(IsStringASCII(ascii
));
184 size_t length
= strlen(ascii
);
185 if (length
<= kMaxStringBytesForCopy
)
186 return v8::String::NewFromUtf8(isolate
, ascii
, v8::String::kNormalString
,
188 return v8::String::NewExternal(isolate
,
189 new V8ExternalASCIILiteral(ascii
, length
));
192 // Stringizes a V8 object by calling its toString() method. Returns true
193 // on success. This may fail if the toString() throws an exception.
194 bool V8ObjectToUTF16String(v8::Handle
<v8::Value
> object
,
195 base::string16
* utf16_result
,
196 v8::Isolate
* isolate
) {
197 if (object
.IsEmpty())
200 v8::HandleScope
scope(isolate
);
201 v8::Local
<v8::String
> str_object
= object
->ToString();
202 if (str_object
.IsEmpty())
204 *utf16_result
= V8StringToUTF16(str_object
);
208 // Extracts an hostname argument from |args|. On success returns true
209 // and fills |*hostname| with the result.
210 bool GetHostnameArgument(const v8::FunctionCallbackInfo
<v8::Value
>& args
,
211 std::string
* hostname
) {
212 // The first argument should be a string.
213 if (args
.Length() == 0 || args
[0].IsEmpty() || !args
[0]->IsString())
216 const base::string16 hostname_utf16
= V8StringToUTF16(args
[0]->ToString());
218 // If the hostname is already in ASCII, simply return it as is.
219 if (IsStringASCII(hostname_utf16
)) {
220 *hostname
= UTF16ToASCII(hostname_utf16
);
224 // Otherwise try to convert it from IDN to punycode.
225 const int kInitialBufferSize
= 256;
226 url_canon::RawCanonOutputT
<base::char16
, kInitialBufferSize
> punycode_output
;
227 if (!url_canon::IDNToASCII(hostname_utf16
.data(),
228 hostname_utf16
.length(),
233 // |punycode_output| should now be ASCII; convert it to a std::string.
234 // (We could use UTF16ToASCII() instead, but that requires an extra string
235 // copy. Since ASCII is a subset of UTF8 the following is equivalent).
236 bool success
= base::UTF16ToUTF8(punycode_output
.data(),
237 punycode_output
.length(),
240 DCHECK(IsStringASCII(*hostname
));
244 // Wrapper for passing around IP address strings and IPAddressNumber objects.
246 IPAddress(const std::string
& ip_string
, const IPAddressNumber
& ip_number
)
247 : string_value(ip_string
),
248 ip_address_number(ip_number
) {
251 // Used for sorting IP addresses in ascending order in SortIpAddressList().
252 // IP6 addresses are placed ahead of IPv4 addresses.
253 bool operator<(const IPAddress
& rhs
) const {
254 const IPAddressNumber
& ip1
= this->ip_address_number
;
255 const IPAddressNumber
& ip2
= rhs
.ip_address_number
;
256 if (ip1
.size() != ip2
.size())
257 return ip1
.size() > ip2
.size(); // IPv6 before IPv4.
258 DCHECK(ip1
.size() == ip2
.size());
259 return memcmp(&ip1
[0], &ip2
[0], ip1
.size()) < 0; // Ascending order.
262 std::string string_value
;
263 IPAddressNumber ip_address_number
;
266 // Handler for "sortIpAddressList(IpAddressList)". |ip_address_list| is a
267 // semi-colon delimited string containing IP addresses.
268 // |sorted_ip_address_list| is the resulting list of sorted semi-colon delimited
269 // IP addresses or an empty string if unable to sort the IP address list.
270 // Returns 'true' if the sorting was successful, and 'false' if the input was an
271 // empty string, a string of separators (";" in this case), or if any of the IP
272 // addresses in the input list failed to parse.
273 bool SortIpAddressList(const std::string
& ip_address_list
,
274 std::string
* sorted_ip_address_list
) {
275 sorted_ip_address_list
->clear();
277 // Strip all whitespace (mimics IE behavior).
278 std::string cleaned_ip_address_list
;
279 base::RemoveChars(ip_address_list
, " \t", &cleaned_ip_address_list
);
280 if (cleaned_ip_address_list
.empty())
283 // Split-up IP addresses and store them in a vector.
284 std::vector
<IPAddress
> ip_vector
;
285 IPAddressNumber ip_num
;
286 base::StringTokenizer
str_tok(cleaned_ip_address_list
, ";");
287 while (str_tok
.GetNext()) {
288 if (!ParseIPLiteralToNumber(str_tok
.token(), &ip_num
))
290 ip_vector
.push_back(IPAddress(str_tok
.token(), ip_num
));
293 if (ip_vector
.empty()) // Can happen if we have something like
294 return false; // sortIpAddressList(";") or sortIpAddressList("; ;")
296 DCHECK(!ip_vector
.empty());
298 // Sort lists according to ascending numeric value.
299 if (ip_vector
.size() > 1)
300 std::stable_sort(ip_vector
.begin(), ip_vector
.end());
302 // Return a semi-colon delimited list of sorted addresses (IPv6 followed by
304 for (size_t i
= 0; i
< ip_vector
.size(); ++i
) {
306 *sorted_ip_address_list
+= ";";
307 *sorted_ip_address_list
+= ip_vector
[i
].string_value
;
312 // Handler for "isInNetEx(ip_address, ip_prefix)". |ip_address| is a string
313 // containing an IPv4/IPv6 address, and |ip_prefix| is a string containg a
314 // slash-delimited IP prefix with the top 'n' bits specified in the bit
315 // field. This returns 'true' if the address is in the same subnet, and
316 // 'false' otherwise. Also returns 'false' if the prefix is in an incorrect
317 // format, or if an address and prefix of different types are used (e.g. IPv6
318 // address and IPv4 prefix).
319 bool IsInNetEx(const std::string
& ip_address
, const std::string
& ip_prefix
) {
320 IPAddressNumber address
;
321 if (!ParseIPLiteralToNumber(ip_address
, &address
))
324 IPAddressNumber prefix
;
325 size_t prefix_length_in_bits
;
326 if (!ParseCIDRBlock(ip_prefix
, &prefix
, &prefix_length_in_bits
))
329 // Both |address| and |prefix| must be of the same type (IPv4 or IPv6).
330 if (address
.size() != prefix
.size())
333 DCHECK((address
.size() == 4 && prefix
.size() == 4) ||
334 (address
.size() == 16 && prefix
.size() == 16));
336 return IPNumberMatchesPrefix(address
, prefix
, prefix_length_in_bits
);
341 // ProxyResolverV8::Context ---------------------------------------------------
343 class ProxyResolverV8::Context
{
345 Context(ProxyResolverV8
* parent
, v8::Isolate
* isolate
)
352 v8::Locker
locked(isolate_
);
353 v8::Isolate::Scope
isolate_scope(isolate_
);
359 JSBindings
* js_bindings() {
360 return parent_
->js_bindings_
;
363 int ResolveProxy(const GURL
& query_url
, ProxyInfo
* results
) {
364 v8::Locker
locked(isolate_
);
365 v8::Isolate::Scope
isolate_scope(isolate_
);
366 v8::HandleScope
scope(isolate_
);
368 v8::Local
<v8::Context
> context
=
369 v8::Local
<v8::Context
>::New(isolate_
, v8_context_
);
370 v8::Context::Scope
function_scope(context
);
372 v8::Local
<v8::Value
> function
;
373 if (!GetFindProxyForURL(&function
)) {
374 js_bindings()->OnError(
375 -1, base::ASCIIToUTF16("FindProxyForURL() is undefined."));
376 return ERR_PAC_SCRIPT_FAILED
;
379 v8::Handle
<v8::Value
> argv
[] = {
380 ASCIIStringToV8String(isolate_
, query_url
.spec()),
381 ASCIIStringToV8String(isolate_
, query_url
.HostNoBrackets()),
384 v8::TryCatch try_catch
;
385 v8::Local
<v8::Value
> ret
= v8::Function::Cast(*function
)->Call(
386 context
->Global(), arraysize(argv
), argv
);
388 if (try_catch
.HasCaught()) {
389 HandleError(try_catch
.Message());
390 return ERR_PAC_SCRIPT_FAILED
;
393 if (!ret
->IsString()) {
394 js_bindings()->OnError(
395 -1, base::ASCIIToUTF16("FindProxyForURL() did not return a string."));
396 return ERR_PAC_SCRIPT_FAILED
;
399 base::string16 ret_str
= V8StringToUTF16(ret
->ToString());
401 if (!IsStringASCII(ret_str
)) {
402 // TODO(eroman): Rather than failing when a wide string is returned, we
403 // could extend the parsing to handle IDNA hostnames by
404 // converting them to ASCII punycode.
406 base::string16 error_message
=
407 base::ASCIIToUTF16("FindProxyForURL() returned a non-ASCII string "
408 "(crbug.com/47234): ") + ret_str
;
409 js_bindings()->OnError(-1, error_message
);
410 return ERR_PAC_SCRIPT_FAILED
;
413 results
->UsePacString(UTF16ToASCII(ret_str
));
417 int InitV8(const scoped_refptr
<ProxyResolverScriptData
>& pac_script
) {
418 v8::Locker
locked(isolate_
);
419 v8::Isolate::Scope
isolate_scope(isolate_
);
420 v8::HandleScope
scope(isolate_
);
422 v8_this_
.Reset(isolate_
, v8::External::New(isolate_
, this));
423 v8::Local
<v8::External
> v8_this
=
424 v8::Local
<v8::External
>::New(isolate_
, v8_this_
);
425 v8::Local
<v8::ObjectTemplate
> global_template
=
426 v8::ObjectTemplate::New(isolate_
);
428 // Attach the javascript bindings.
429 v8::Local
<v8::FunctionTemplate
> alert_template
=
430 v8::FunctionTemplate::New(isolate_
, &AlertCallback
, v8_this
);
431 global_template
->Set(ASCIILiteralToV8String(isolate_
, "alert"),
434 v8::Local
<v8::FunctionTemplate
> my_ip_address_template
=
435 v8::FunctionTemplate::New(isolate_
, &MyIpAddressCallback
, v8_this
);
436 global_template
->Set(ASCIILiteralToV8String(isolate_
, "myIpAddress"),
437 my_ip_address_template
);
439 v8::Local
<v8::FunctionTemplate
> dns_resolve_template
=
440 v8::FunctionTemplate::New(isolate_
, &DnsResolveCallback
, v8_this
);
441 global_template
->Set(ASCIILiteralToV8String(isolate_
, "dnsResolve"),
442 dns_resolve_template
);
444 // Microsoft's PAC extensions:
446 v8::Local
<v8::FunctionTemplate
> dns_resolve_ex_template
=
447 v8::FunctionTemplate::New(isolate_
, &DnsResolveExCallback
, v8_this
);
448 global_template
->Set(ASCIILiteralToV8String(isolate_
, "dnsResolveEx"),
449 dns_resolve_ex_template
);
451 v8::Local
<v8::FunctionTemplate
> my_ip_address_ex_template
=
452 v8::FunctionTemplate::New(isolate_
, &MyIpAddressExCallback
, v8_this
);
453 global_template
->Set(ASCIILiteralToV8String(isolate_
, "myIpAddressEx"),
454 my_ip_address_ex_template
);
456 v8::Local
<v8::FunctionTemplate
> sort_ip_address_list_template
=
457 v8::FunctionTemplate::New(isolate_
,
458 &SortIpAddressListCallback
,
460 global_template
->Set(ASCIILiteralToV8String(isolate_
, "sortIpAddressList"),
461 sort_ip_address_list_template
);
463 v8::Local
<v8::FunctionTemplate
> is_in_net_ex_template
=
464 v8::FunctionTemplate::New(isolate_
, &IsInNetExCallback
, v8_this
);
465 global_template
->Set(ASCIILiteralToV8String(isolate_
, "isInNetEx"),
466 is_in_net_ex_template
);
469 isolate_
, v8::Context::New(isolate_
, NULL
, global_template
));
471 v8::Local
<v8::Context
> context
=
472 v8::Local
<v8::Context
>::New(isolate_
, v8_context_
);
473 v8::Context::Scope
ctx(context
);
475 // Add the PAC utility functions to the environment.
476 // (This script should never fail, as it is a string literal!)
477 // Note that the two string literals are concatenated.
479 ASCIILiteralToV8String(
481 PROXY_RESOLVER_SCRIPT
482 PROXY_RESOLVER_SCRIPT_EX
),
483 kPacUtilityResourceName
);
489 // Add the user's PAC code to the environment.
491 RunScript(ScriptDataToV8String(isolate_
, pac_script
), kPacResourceName
);
495 // At a minimum, the FindProxyForURL() function must be defined for this
496 // to be a legitimiate PAC script.
497 v8::Local
<v8::Value
> function
;
498 if (!GetFindProxyForURL(&function
)) {
499 js_bindings()->OnError(
500 -1, base::ASCIIToUTF16("FindProxyForURL() is undefined."));
501 return ERR_PAC_SCRIPT_FAILED
;
508 v8::Locker
locked(isolate_
);
509 v8::Isolate::Scope
isolate_scope(isolate_
);
510 v8::V8::LowMemoryNotification();
514 bool GetFindProxyForURL(v8::Local
<v8::Value
>* function
) {
515 v8::Local
<v8::Context
> context
=
516 v8::Local
<v8::Context
>::New(isolate_
, v8_context_
);
518 context
->Global()->Get(
519 ASCIILiteralToV8String(isolate_
, "FindProxyForURL"));
520 return (*function
)->IsFunction();
523 // Handle an exception thrown by V8.
524 void HandleError(v8::Handle
<v8::Message
> message
) {
525 base::string16 error_message
;
526 int line_number
= -1;
528 if (!message
.IsEmpty()) {
529 line_number
= message
->GetLineNumber();
530 V8ObjectToUTF16String(message
->Get(), &error_message
, isolate_
);
533 js_bindings()->OnError(line_number
, error_message
);
536 // Compiles and runs |script| in the current V8 context.
537 // Returns OK on success, otherwise an error code.
538 int RunScript(v8::Handle
<v8::String
> script
, const char* script_name
) {
539 v8::TryCatch try_catch
;
541 // Compile the script.
542 v8::ScriptOrigin origin
=
543 v8::ScriptOrigin(ASCIILiteralToV8String(isolate_
, script_name
));
544 v8::Local
<v8::Script
> code
= v8::Script::Compile(script
, &origin
);
551 if (try_catch
.HasCaught()) {
552 HandleError(try_catch
.Message());
553 return ERR_PAC_SCRIPT_FAILED
;
559 // V8 callback for when "alert()" is invoked by the PAC script.
560 static void AlertCallback(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
562 static_cast<Context
*>(v8::External::Cast(*args
.Data())->Value());
564 // Like firefox we assume "undefined" if no argument was specified, and
565 // disregard any arguments beyond the first.
566 base::string16 message
;
567 if (args
.Length() == 0) {
568 message
= base::ASCIIToUTF16("undefined");
570 if (!V8ObjectToUTF16String(args
[0], &message
, args
.GetIsolate()))
571 return; // toString() threw an exception.
574 context
->js_bindings()->Alert(message
);
577 // V8 callback for when "myIpAddress()" is invoked by the PAC script.
578 static void MyIpAddressCallback(
579 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
580 DnsResolveCallbackHelper(args
, JSBindings::MY_IP_ADDRESS
);
583 // V8 callback for when "myIpAddressEx()" is invoked by the PAC script.
584 static void MyIpAddressExCallback(
585 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
586 DnsResolveCallbackHelper(args
, JSBindings::MY_IP_ADDRESS_EX
);
589 // V8 callback for when "dnsResolve()" is invoked by the PAC script.
590 static void DnsResolveCallback(
591 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
592 DnsResolveCallbackHelper(args
, JSBindings::DNS_RESOLVE
);
595 // V8 callback for when "dnsResolveEx()" is invoked by the PAC script.
596 static void DnsResolveExCallback(
597 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
598 DnsResolveCallbackHelper(args
, JSBindings::DNS_RESOLVE_EX
);
601 // Shared code for implementing:
602 // - myIpAddress(), myIpAddressEx(), dnsResolve(), dnsResolveEx().
603 static void DnsResolveCallbackHelper(
604 const v8::FunctionCallbackInfo
<v8::Value
>& args
,
605 JSBindings::ResolveDnsOperation op
) {
607 static_cast<Context
*>(v8::External::Cast(*args
.Data())->Value());
609 std::string hostname
;
611 // dnsResolve() and dnsResolveEx() need at least 1 argument.
612 if (op
== JSBindings::DNS_RESOLVE
|| op
== JSBindings::DNS_RESOLVE_EX
) {
613 if (!GetHostnameArgument(args
, &hostname
)) {
614 if (op
== JSBindings::DNS_RESOLVE
)
615 args
.GetReturnValue().SetNull();
622 bool terminate
= false;
625 v8::Unlocker
unlocker(args
.GetIsolate());
626 success
= context
->js_bindings()->ResolveDns(
627 hostname
, op
, &result
, &terminate
);
631 v8::V8::TerminateExecution(args
.GetIsolate());
634 args
.GetReturnValue().Set(
635 ASCIIStringToV8String(args
.GetIsolate(), result
));
639 // Each function handles resolution errors differently.
641 case JSBindings::DNS_RESOLVE
:
642 args
.GetReturnValue().SetNull();
644 case JSBindings::DNS_RESOLVE_EX
:
645 args
.GetReturnValue().SetEmptyString();
647 case JSBindings::MY_IP_ADDRESS
:
648 args
.GetReturnValue().Set(
649 ASCIILiteralToV8String(args
.GetIsolate(), "127.0.0.1"));
651 case JSBindings::MY_IP_ADDRESS_EX
:
652 args
.GetReturnValue().SetEmptyString();
659 // V8 callback for when "sortIpAddressList()" is invoked by the PAC script.
660 static void SortIpAddressListCallback(
661 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
662 // We need at least one string argument.
663 if (args
.Length() == 0 || args
[0].IsEmpty() || !args
[0]->IsString()) {
664 args
.GetReturnValue().SetNull();
668 std::string ip_address_list
= V8StringToUTF8(args
[0]->ToString());
669 if (!IsStringASCII(ip_address_list
)) {
670 args
.GetReturnValue().SetNull();
673 std::string sorted_ip_address_list
;
674 bool success
= SortIpAddressList(ip_address_list
, &sorted_ip_address_list
);
676 args
.GetReturnValue().Set(false);
679 args
.GetReturnValue().Set(
680 ASCIIStringToV8String(args
.GetIsolate(), sorted_ip_address_list
));
683 // V8 callback for when "isInNetEx()" is invoked by the PAC script.
684 static void IsInNetExCallback(
685 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
686 // We need at least 2 string arguments.
687 if (args
.Length() < 2 || args
[0].IsEmpty() || !args
[0]->IsString() ||
688 args
[1].IsEmpty() || !args
[1]->IsString()) {
689 args
.GetReturnValue().SetNull();
693 std::string ip_address
= V8StringToUTF8(args
[0]->ToString());
694 if (!IsStringASCII(ip_address
)) {
695 args
.GetReturnValue().Set(false);
698 std::string ip_prefix
= V8StringToUTF8(args
[1]->ToString());
699 if (!IsStringASCII(ip_prefix
)) {
700 args
.GetReturnValue().Set(false);
703 args
.GetReturnValue().Set(IsInNetEx(ip_address
, ip_prefix
));
706 mutable base::Lock lock_
;
707 ProxyResolverV8
* parent_
;
708 v8::Isolate
* isolate_
;
709 v8::Persistent
<v8::External
> v8_this_
;
710 v8::Persistent
<v8::Context
> v8_context_
;
713 // ProxyResolverV8 ------------------------------------------------------------
715 ProxyResolverV8::ProxyResolverV8()
716 : ProxyResolver(true /*expects_pac_bytes*/),
720 ProxyResolverV8::~ProxyResolverV8() {}
722 int ProxyResolverV8::GetProxyForURL(
723 const GURL
& query_url
, ProxyInfo
* results
,
724 const CompletionCallback
& /*callback*/,
725 RequestHandle
* /*request*/,
726 const BoundNetLog
& net_log
) {
727 DCHECK(js_bindings_
);
729 // If the V8 instance has not been initialized (either because
730 // SetPacScript() wasn't called yet, or because it failed.
734 // Otherwise call into V8.
735 int rv
= context_
->ResolveProxy(query_url
, results
);
740 void ProxyResolverV8::CancelRequest(RequestHandle request
) {
741 // This is a synchronous ProxyResolver; no possibility for async requests.
745 LoadState
ProxyResolverV8::GetLoadState(RequestHandle request
) const {
747 return LOAD_STATE_IDLE
;
750 void ProxyResolverV8::CancelSetPacScript() {
754 void ProxyResolverV8::PurgeMemory() {
756 context_
->PurgeMemory();
759 int ProxyResolverV8::SetPacScript(
760 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
761 const CompletionCallback
& /*callback*/) {
762 DCHECK(script_data
.get());
763 DCHECK(js_bindings_
);
766 if (script_data
->utf16().empty())
767 return ERR_PAC_SCRIPT_FAILED
;
769 // Try parsing the PAC script.
770 scoped_ptr
<Context
> context(new Context(this, GetDefaultIsolate()));
771 int rv
= context
->InitV8(script_data
);
773 context_
.reset(context
.release());
778 void ProxyResolverV8::RememberDefaultIsolate() {
779 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
781 << "ProxyResolverV8::RememberDefaultIsolate called on wrong thread";
782 DCHECK(g_default_isolate_
== NULL
|| g_default_isolate_
== isolate
)
783 << "Default Isolate can not be changed";
784 g_default_isolate_
= isolate
;
789 void ProxyResolverV8::CreateIsolate() {
790 v8::Isolate
* isolate
= v8::Isolate::New();
792 DCHECK(g_default_isolate_
== NULL
) << "Default Isolate can not be set twice";
795 v8::V8::Initialize();
797 g_default_isolate_
= isolate
;
799 #endif // defined(OS_WIN)
802 v8::Isolate
* ProxyResolverV8::GetDefaultIsolate() {
803 DCHECK(g_default_isolate_
)
804 << "Must call ProxyResolverV8::RememberDefaultIsolate() first";
805 return g_default_isolate_
;
808 v8::Isolate
* ProxyResolverV8::g_default_isolate_
= NULL
;
811 size_t ProxyResolverV8::GetTotalHeapSize() {
812 if (!g_default_isolate_
)
815 v8::Locker
locked(g_default_isolate_
);
816 v8::Isolate::Scope
isolate_scope(g_default_isolate_
);
817 v8::HeapStatistics heap_statistics
;
818 g_default_isolate_
->GetHeapStatistics(&heap_statistics
);
819 return heap_statistics
.total_heap_size();
823 size_t ProxyResolverV8::GetUsedHeapSize() {
824 if (!g_default_isolate_
)
827 v8::Locker
locked(g_default_isolate_
);
828 v8::Isolate::Scope
isolate_scope(g_default_isolate_
);
829 v8::HeapStatistics heap_statistics
;
830 g_default_isolate_
->GetHeapStatistics(&heap_statistics
);
831 return heap_statistics
.used_heap_size();