OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2013 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 "net/proxy/proxy_resolver_v8_tracing.h" |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/message_loop_proxy.h" |
| 9 #include "base/stringprintf.h" |
| 10 #include "base/synchronization/cancellation_flag.h" |
| 11 #include "base/synchronization/waitable_event.h" |
| 12 #include "base/threading/thread.h" |
| 13 #include "base/threading/thread_restrictions.h" |
| 14 #include "base/values.h" |
| 15 #include "net/base/address_list.h" |
| 16 #include "net/base/host_resolver.h" |
| 17 #include "net/base/net_errors.h" |
| 18 #include "net/base/net_log.h" |
| 19 #include "net/proxy/proxy_info.h" |
| 20 #include "net/proxy/proxy_resolver_error_observer.h" |
| 21 #include "net/proxy/proxy_resolver_v8.h" |
| 22 |
| 23 // The intent of this class is explained in the design document: |
| 24 // https://docs.google.com/a/chromium.org/document/d/16Ij5OcVnR3s0MH4Z5XkhI9VTPo
MJdaBn9rKreAmGOdE/edit |
| 25 // |
| 26 // In a nutshell, PAC scripts are Javascript programs and may depend on |
| 27 // network I/O, by calling functions like dnsResolve(). |
| 28 // |
| 29 // This is problematic since functions such as dnsResolve() will block the |
| 30 // Javascript execution until the DNS result is availble, thereby stalling the |
| 31 // PAC thread, which hurts the ability to process parallel proxy resolves. |
| 32 // An obvious solution is to simply start more PAC threads, however this scales |
| 33 // poorly, which hurts the ability to process parallel proxy resolves. |
| 34 // |
| 35 // The solution in ProxyResolverV8Tracing is to model PAC scripts as being |
| 36 // deterministic, and depending only on the inputted URL. When the script |
| 37 // issues a dnsResolve() for a yet unresolved hostname, the Javascript |
| 38 // execution is "aborted", and then re-started once the DNS result is |
| 39 // known. |
| 40 namespace net { |
| 41 |
| 42 namespace { |
| 43 |
| 44 // Upper bound on how many *unique* DNS resolves a PAC script is allowed |
| 45 // to make. This is a failsafe both for scripts that do a ridiculous |
| 46 // number of DNS resolves, as well as scripts which are misbehaving |
| 47 // under the tracing optimization. It is not expected to hit this normally. |
| 48 const size_t kMaxUniqueResolveDnsPerExec = 20; |
| 49 |
| 50 // Approximate number of bytes to use for buffering alerts() and errors. |
| 51 // This is a failsafe in case repeated executions of the script causes |
| 52 // too much memory bloat. It is not expected for well behaved scripts to |
| 53 // hit this. (In fact normal scripts should not even have alerts() or errors). |
| 54 const size_t kMaxAlertsAndErrorsBytes = 2048; |
| 55 |
| 56 // Returns event parameters for a PAC error message (line number + message). |
| 57 base::Value* NetLogErrorCallback(int line_number, |
| 58 const string16* message, |
| 59 NetLog::LogLevel /* log_level */) { |
| 60 base::DictionaryValue* dict = new base::DictionaryValue(); |
| 61 dict->SetInteger("line_number", line_number); |
| 62 dict->SetString("message", *message); |
| 63 return dict; |
| 64 } |
| 65 |
| 66 } // namespace |
| 67 |
| 68 // The Job class is responsible for executing GetProxyForURL() and |
| 69 // SetPacScript(), since both of these operations share similar code. |
| 70 // |
| 71 // The DNS for these operations can operate in either blocking or |
| 72 // non-blocking mode. Blocking mode is used as a fallback when the PAC script |
| 73 // seems to be misbehaving under the tracing optimization. |
| 74 // |
| 75 // Note that this class runs on both the origin thread and a worker |
| 76 // thread. Most methods are expected to be used exclusively on one thread |
| 77 // or the other. |
| 78 // |
| 79 // The lifetime of Jobs does not exceed that of the ProxyResolverV8Tracing that |
| 80 // spawned it. Destruction might happen on either the origin thread or the |
| 81 // worker thread. |
| 82 class ProxyResolverV8Tracing::Job |
| 83 : public base::RefCountedThreadSafe<ProxyResolverV8Tracing::Job>, |
| 84 public ProxyResolverV8::JSBindings { |
| 85 public: |
| 86 // |parent| is non-owned. It is the ProxyResolverV8Tracing that spawned this |
| 87 // Job, and must oulive it. |
| 88 explicit Job(ProxyResolverV8Tracing* parent); |
| 89 |
| 90 // Called from origin thread. |
| 91 void StartSetPacScript( |
| 92 const scoped_refptr<ProxyResolverScriptData>& script_data, |
| 93 const CompletionCallback& callback); |
| 94 |
| 95 // Called from origin thread. |
| 96 void StartGetProxyForURL(const GURL& url, |
| 97 ProxyInfo* results, |
| 98 const BoundNetLog& net_log, |
| 99 const CompletionCallback& callback); |
| 100 |
| 101 // Called from origin thread. |
| 102 void Cancel(); |
| 103 |
| 104 // Called from origin thread. |
| 105 LoadState GetLoadState() const; |
| 106 |
| 107 private: |
| 108 typedef std::map<std::string, std::string> DnsCache; |
| 109 friend class base::RefCountedThreadSafe<ProxyResolverV8Tracing::Job>; |
| 110 |
| 111 enum Operation { |
| 112 SET_PAC_SCRIPT, |
| 113 GET_PROXY_FOR_URL, |
| 114 }; |
| 115 |
| 116 struct AlertOrError { |
| 117 bool is_alert; |
| 118 int line_number; |
| 119 string16 message; |
| 120 }; |
| 121 |
| 122 ~Job(); |
| 123 |
| 124 void CheckIsOnWorkerThread() const; |
| 125 void CheckIsOnOriginThread() const; |
| 126 |
| 127 void SetCallback(const CompletionCallback& callback); |
| 128 void ReleaseCallback(); |
| 129 |
| 130 ProxyResolverV8* v8_resolver(); |
| 131 MessageLoop* worker_loop(); |
| 132 HostResolver* host_resolver(); |
| 133 ProxyResolverErrorObserver* error_observer(); |
| 134 NetLog* net_log(); |
| 135 |
| 136 // Invokes the user's callback. |
| 137 void NotifyCaller(int result); |
| 138 void NotifyCallerOnOriginLoop(int result); |
| 139 |
| 140 void Start(Operation op, bool blocking_dns, |
| 141 const CompletionCallback& callback); |
| 142 |
| 143 void ExecuteBlocking(); |
| 144 void ExecuteNonBlocking(); |
| 145 int ExecuteProxyResolver(); |
| 146 |
| 147 // Implementation of ProxyResolverv8::JSBindings |
| 148 virtual bool ResolveDns(const std::string& host, |
| 149 ResolveDnsOperation op, |
| 150 std::string* output) OVERRIDE; |
| 151 virtual void Alert(const string16& message) OVERRIDE; |
| 152 virtual void OnError(int line_number, const string16& error) OVERRIDE; |
| 153 |
| 154 bool ResolveDnsBlocking(const std::string& host, |
| 155 ResolveDnsOperation op, |
| 156 std::string* output); |
| 157 |
| 158 bool ResolveDnsNonBlocking(const std::string& host, |
| 159 ResolveDnsOperation op, |
| 160 std::string* output); |
| 161 |
| 162 void DoDnsOperation(const std::string& host, ResolveDnsOperation op, |
| 163 bool* out_cache_hit); |
| 164 void OnDnsOperationComplete(int result); |
| 165 |
| 166 void ScheduleRestartWithBlockingDns(); |
| 167 |
| 168 bool GetDnsFromLocalCache(const std::string& host, ResolveDnsOperation op, |
| 169 std::string* output, bool* return_value); |
| 170 |
| 171 void SaveDnsToLocalCache(const std::string& host, ResolveDnsOperation op, |
| 172 int net_error, const net::AddressList& addresses); |
| 173 |
| 174 // Builds a RequestInfo to service the specified PAC DNS operation. |
| 175 static HostResolver::RequestInfo MakeDnsRequestInfo(const std::string& host, |
| 176 ResolveDnsOperation op); |
| 177 |
| 178 // Makes a key for looking up |host, op| in |dns_cache_|. Strings are used for |
| 179 // convenience, to avoid defining custom comparators. |
| 180 static std::string MakeDnsCacheKey(const std::string& host, |
| 181 ResolveDnsOperation op); |
| 182 |
| 183 void HandleAlertOrError(bool is_alert, int line_number, |
| 184 const string16& message); |
| 185 void DispatchBufferedAlertsAndErrors(); |
| 186 void DispatchAlertOrError(bool is_alert, int line_number, |
| 187 const string16& message); |
| 188 |
| 189 void LogEventToCurrentRequestAndGlobally( |
| 190 NetLog::EventType type, |
| 191 const NetLog::ParametersCallback& parameters_callback); |
| 192 |
| 193 // The thread which called into ProxyResolverV8Tracing, and on which the |
| 194 // completion callback is expected to run. |
| 195 scoped_refptr<base::MessageLoopProxy> origin_loop_; |
| 196 |
| 197 // The ProxyResolverV8Tracing which spawned this Job. |
| 198 // Initialized on origin thread and then accessed from both threads. |
| 199 ProxyResolverV8Tracing* parent_; |
| 200 |
| 201 // The callback to run (on the origin thread) when the Job finishes. |
| 202 // Should only be accessed from origin thread. |
| 203 CompletionCallback callback_; |
| 204 |
| 205 // Flag to indicate whether the request has been cancelled. |
| 206 base::CancellationFlag cancelled_; |
| 207 |
| 208 // The operation that this Job is running. |
| 209 // Initialized on origin thread and then accessed from both threads. |
| 210 Operation operation_; |
| 211 |
| 212 // The DNS mode for this Job. |
| 213 // Initialized on origin thread, mutated on worker thread, and accessed |
| 214 // by both the origin thread and worker thread. |
| 215 bool blocking_dns_; |
| 216 |
| 217 // Used to block the worker thread on a DNS operation taking place on the |
| 218 // origin thread. |
| 219 base::WaitableEvent event_; |
| 220 |
| 221 // Map of DNS operations completed so far. Written into on the origin thread |
| 222 // and read on the worker thread. |
| 223 DnsCache dns_cache_; |
| 224 |
| 225 // ------------------------------------------------------- |
| 226 // State specific to SET_PAC_SCRIPT. |
| 227 // ------------------------------------------------------- |
| 228 |
| 229 scoped_refptr<ProxyResolverScriptData> script_data_; |
| 230 |
| 231 // ------------------------------------------------------- |
| 232 // State specific to GET_PROXY_FOR_URL. |
| 233 // ------------------------------------------------------- |
| 234 |
| 235 ProxyInfo* user_results_; // Owned by caller, lives on origin thread. |
| 236 GURL url_; |
| 237 ProxyInfo results_; |
| 238 BoundNetLog bound_net_log_; |
| 239 |
| 240 // --------------------------------------------------------------------------- |
| 241 // State for ExecuteNonBlocking() |
| 242 // --------------------------------------------------------------------------- |
| 243 // These variables are used exclusively on the worker thread and are only |
| 244 // meaningful when executing inside of ExecuteNonBlocking(). |
| 245 |
| 246 // Whether this execution was abandoned due to a missing DNS dependency. |
| 247 bool abandoned_; |
| 248 |
| 249 // Number of calls made to ResolveDns() by this execution. |
| 250 int num_dns_; |
| 251 |
| 252 // Sequence of calls made to Alert() or OnError() by this execution. |
| 253 std::vector<AlertOrError> alerts_and_errors_; |
| 254 size_t alerts_and_errors_byte_cost_; // Approximate byte cost of the above. |
| 255 |
| 256 // Number of calls made to ResolveDns() by the PREVIOUS execution. |
| 257 int last_num_dns_; |
| 258 |
| 259 // Whether the current execution needs to be restarted in blocking mode. |
| 260 bool should_restart_with_blocking_dns_; |
| 261 |
| 262 // --------------------------------------------------------------------------- |
| 263 // State for pending DNS request. |
| 264 // --------------------------------------------------------------------------- |
| 265 // These variables are used exclusively on the origin thread. |
| 266 |
| 267 HostResolver::RequestHandle pending_dns_; |
| 268 // Only meaningful when |pending_dns_|: |
| 269 std::string pending_dns_host_; |
| 270 ResolveDnsOperation pending_dns_op_; |
| 271 AddressList pending_dns_addresses_; |
| 272 }; |
| 273 |
| 274 ProxyResolverV8Tracing::Job::Job(ProxyResolverV8Tracing* parent) |
| 275 : origin_loop_(base::MessageLoopProxy::current()), |
| 276 parent_(parent), |
| 277 event_(true, false), |
| 278 last_num_dns_(0), |
| 279 pending_dns_(NULL) { |
| 280 CheckIsOnOriginThread(); |
| 281 } |
| 282 |
| 283 void ProxyResolverV8Tracing::Job::StartSetPacScript( |
| 284 const scoped_refptr<ProxyResolverScriptData>& script_data, |
| 285 const CompletionCallback& callback) { |
| 286 CheckIsOnOriginThread(); |
| 287 |
| 288 script_data_ = script_data; |
| 289 |
| 290 // Script initialization uses blocking DNS since there isn't any |
| 291 // advantage to using non-blocking mode here. That is because the |
| 292 // parent ProxyService can't submit any ProxyResolve requests until |
| 293 // initialization has completed successfully! |
| 294 Start(SET_PAC_SCRIPT, true /*blocking*/, callback); |
| 295 } |
| 296 |
| 297 void ProxyResolverV8Tracing::Job::StartGetProxyForURL( |
| 298 const GURL& url, |
| 299 ProxyInfo* results, |
| 300 const BoundNetLog& net_log, |
| 301 const CompletionCallback& callback) { |
| 302 CheckIsOnOriginThread(); |
| 303 |
| 304 url_ = url; |
| 305 user_results_ = results; |
| 306 bound_net_log_ = net_log; |
| 307 |
| 308 Start(GET_PROXY_FOR_URL, false /*non-blocking*/, callback); |
| 309 } |
| 310 |
| 311 void ProxyResolverV8Tracing::Job::Cancel() { |
| 312 CheckIsOnOriginThread(); |
| 313 |
| 314 // There are several possibilities to consider for cancellation: |
| 315 // (a) The job has been posted to the worker thread, however script execution |
| 316 // has not yet started. |
| 317 // (b) The script is executing on the worker thread. |
| 318 // (c) The script is executing on the worker thread, however is blocked inside |
| 319 // of dnsResolve() waiting for a response from the origin thread. |
| 320 // (d) Nothing is running on the worker thread, however the host resolver has |
| 321 // a pending DNS request which upon completion will restart the script |
| 322 // execution. |
| 323 // (e) The worker thread has a pending task to restart execution, which was |
| 324 // posted after the DNS dependency was resolved and saved to local cache. |
| 325 // (f) The script execution completed entirely, and posted a task to the |
| 326 // origin thread to notify the caller. |
| 327 // |
| 328 // |cancelled_| is read on both the origin thread and worker thread. The |
| 329 // code that runs on the worker thread is littered with checks on |
| 330 // |cancelled_| to break out early. |
| 331 cancelled_.Set(); |
| 332 |
| 333 ReleaseCallback(); |
| 334 |
| 335 if (pending_dns_) { |
| 336 host_resolver()->CancelRequest(pending_dns_); |
| 337 pending_dns_ = NULL; |
| 338 } |
| 339 |
| 340 // The worker thread might be blocked waiting for DNS. |
| 341 event_.Signal(); |
| 342 |
| 343 Release(); |
| 344 } |
| 345 |
| 346 LoadState ProxyResolverV8Tracing::Job::GetLoadState() const { |
| 347 CheckIsOnOriginThread(); |
| 348 |
| 349 if (pending_dns_) |
| 350 return LOAD_STATE_RESOLVING_HOST_IN_PROXY_SCRIPT; |
| 351 |
| 352 return LOAD_STATE_RESOLVING_PROXY_FOR_URL; |
| 353 } |
| 354 |
| 355 ProxyResolverV8Tracing::Job::~Job() { |
| 356 DCHECK(!pending_dns_); |
| 357 DCHECK(callback_.is_null()); |
| 358 } |
| 359 |
| 360 void ProxyResolverV8Tracing::Job::CheckIsOnWorkerThread() const { |
| 361 DCHECK_EQ(MessageLoop::current(), parent_->thread_->message_loop()); |
| 362 } |
| 363 |
| 364 void ProxyResolverV8Tracing::Job::CheckIsOnOriginThread() const { |
| 365 DCHECK(origin_loop_->BelongsToCurrentThread()); |
| 366 } |
| 367 |
| 368 void ProxyResolverV8Tracing::Job::SetCallback( |
| 369 const CompletionCallback& callback) { |
| 370 CheckIsOnOriginThread(); |
| 371 DCHECK(callback_.is_null()); |
| 372 parent_->num_outstanding_callbacks_++; |
| 373 callback_ = callback; |
| 374 } |
| 375 |
| 376 void ProxyResolverV8Tracing::Job::ReleaseCallback() { |
| 377 CheckIsOnOriginThread(); |
| 378 DCHECK(!callback_.is_null()); |
| 379 CHECK_GT(parent_->num_outstanding_callbacks_, 0); |
| 380 parent_->num_outstanding_callbacks_--; |
| 381 callback_.Reset(); |
| 382 |
| 383 // For good measure, clear this other user-owned pointer. |
| 384 user_results_ = NULL; |
| 385 } |
| 386 |
| 387 ProxyResolverV8* ProxyResolverV8Tracing::Job::v8_resolver() { |
| 388 return parent_->v8_resolver_.get(); |
| 389 } |
| 390 |
| 391 MessageLoop* ProxyResolverV8Tracing::Job::worker_loop() { |
| 392 return parent_->thread_->message_loop(); |
| 393 } |
| 394 |
| 395 HostResolver* ProxyResolverV8Tracing::Job::host_resolver() { |
| 396 return parent_->host_resolver_; |
| 397 } |
| 398 |
| 399 ProxyResolverErrorObserver* ProxyResolverV8Tracing::Job::error_observer() { |
| 400 return parent_->error_observer_.get(); |
| 401 } |
| 402 |
| 403 NetLog* ProxyResolverV8Tracing::Job::net_log() { |
| 404 return parent_->net_log_; |
| 405 } |
| 406 |
| 407 void ProxyResolverV8Tracing::Job::NotifyCaller(int result) { |
| 408 CheckIsOnWorkerThread(); |
| 409 |
| 410 origin_loop_->PostTask( |
| 411 FROM_HERE, |
| 412 base::Bind(&Job::NotifyCallerOnOriginLoop, this, result)); |
| 413 } |
| 414 |
| 415 void ProxyResolverV8Tracing::Job::NotifyCallerOnOriginLoop(int result) { |
| 416 CheckIsOnOriginThread(); |
| 417 |
| 418 if (cancelled_.IsSet()) |
| 419 return; |
| 420 |
| 421 DCHECK(!callback_.is_null()); |
| 422 DCHECK(!pending_dns_); |
| 423 |
| 424 if (operation_ == GET_PROXY_FOR_URL) |
| 425 *user_results_ = results_; |
| 426 |
| 427 // There is only ever 1 outstanding SET_PAC_SCRIPT job. It needs to be |
| 428 // tracked to support cancellation. |
| 429 if (operation_ == SET_PAC_SCRIPT) { |
| 430 DCHECK_EQ(parent_->set_pac_script_job_.get(), this); |
| 431 parent_->set_pac_script_job_ = NULL; |
| 432 } |
| 433 |
| 434 CompletionCallback callback = callback_; |
| 435 ReleaseCallback(); |
| 436 callback.Run(result); |
| 437 |
| 438 Release(); |
| 439 } |
| 440 |
| 441 void ProxyResolverV8Tracing::Job::Start(Operation op, bool blocking_dns, |
| 442 const CompletionCallback& callback) { |
| 443 CheckIsOnOriginThread(); |
| 444 |
| 445 operation_ = op; |
| 446 blocking_dns_ = blocking_dns; |
| 447 SetCallback(callback); |
| 448 |
| 449 AddRef(); |
| 450 |
| 451 worker_loop()->PostTask(FROM_HERE, |
| 452 blocking_dns_ ? base::Bind(&Job::ExecuteBlocking, this) : |
| 453 base::Bind(&Job::ExecuteNonBlocking, this)); |
| 454 } |
| 455 |
| 456 void ProxyResolverV8Tracing::Job::ExecuteBlocking() { |
| 457 CheckIsOnWorkerThread(); |
| 458 DCHECK(blocking_dns_); |
| 459 |
| 460 if (cancelled_.IsSet()) |
| 461 return; |
| 462 |
| 463 NotifyCaller(ExecuteProxyResolver()); |
| 464 } |
| 465 |
| 466 void ProxyResolverV8Tracing::Job::ExecuteNonBlocking() { |
| 467 CheckIsOnWorkerThread(); |
| 468 DCHECK(!blocking_dns_); |
| 469 |
| 470 if (cancelled_.IsSet()) |
| 471 return; |
| 472 |
| 473 // Reset state for the current execution. |
| 474 abandoned_ = false; |
| 475 num_dns_ = 0; |
| 476 alerts_and_errors_.clear(); |
| 477 alerts_and_errors_byte_cost_ = 0; |
| 478 should_restart_with_blocking_dns_ = false; |
| 479 |
| 480 int result = ExecuteProxyResolver(); |
| 481 |
| 482 if (should_restart_with_blocking_dns_) { |
| 483 DCHECK(!blocking_dns_); |
| 484 DCHECK(abandoned_); |
| 485 blocking_dns_ = true; |
| 486 ExecuteBlocking(); |
| 487 return; |
| 488 } |
| 489 |
| 490 if (abandoned_) |
| 491 return; |
| 492 |
| 493 DispatchBufferedAlertsAndErrors(); |
| 494 NotifyCaller(result); |
| 495 } |
| 496 |
| 497 int ProxyResolverV8Tracing::Job::ExecuteProxyResolver() { |
| 498 JSBindings* prev_bindings = v8_resolver()->js_bindings(); |
| 499 v8_resolver()->set_js_bindings(this); |
| 500 |
| 501 int result = ERR_UNEXPECTED; // Initialized to silence warnings. |
| 502 |
| 503 switch (operation_) { |
| 504 case SET_PAC_SCRIPT: |
| 505 result = v8_resolver()->SetPacScript( |
| 506 script_data_, CompletionCallback()); |
| 507 break; |
| 508 case GET_PROXY_FOR_URL: |
| 509 result = v8_resolver()->GetProxyForURL( |
| 510 url_, |
| 511 // Important: Do not write directly into |user_results_|, since if the |
| 512 // request were to be cancelled from the origin thread, must guarantee |
| 513 // that |user_results_| is not accessed anymore. |
| 514 &results_, |
| 515 CompletionCallback(), |
| 516 NULL, |
| 517 bound_net_log_); |
| 518 break; |
| 519 } |
| 520 |
| 521 v8_resolver()->set_js_bindings(prev_bindings); |
| 522 return result; |
| 523 } |
| 524 |
| 525 bool ProxyResolverV8Tracing::Job::ResolveDns(const std::string& host, |
| 526 ResolveDnsOperation op, |
| 527 std::string* output) { |
| 528 if (cancelled_.IsSet()) |
| 529 return false; |
| 530 |
| 531 if ((op == DNS_RESOLVE || op == DNS_RESOLVE_EX) && host.empty()) { |
| 532 // a DNS resolve with an empty hostname is considered an error. |
| 533 return false; |
| 534 } |
| 535 |
| 536 return blocking_dns_ ? |
| 537 ResolveDnsBlocking(host, op, output) : |
| 538 ResolveDnsNonBlocking(host, op, output); |
| 539 } |
| 540 |
| 541 void ProxyResolverV8Tracing::Job::Alert(const string16& message) { |
| 542 HandleAlertOrError(true, -1, message); |
| 543 } |
| 544 |
| 545 void ProxyResolverV8Tracing::Job::OnError(int line_number, |
| 546 const string16& error) { |
| 547 HandleAlertOrError(false, line_number, error); |
| 548 } |
| 549 |
| 550 bool ProxyResolverV8Tracing::Job::ResolveDnsBlocking(const std::string& host, |
| 551 ResolveDnsOperation op, |
| 552 std::string* output) { |
| 553 CheckIsOnWorkerThread(); |
| 554 |
| 555 // Check if the DNS result for this host has already been cached. |
| 556 bool rv; |
| 557 if (GetDnsFromLocalCache(host, op, output, &rv)) { |
| 558 // Yay, cache hit! |
| 559 return rv; |
| 560 } |
| 561 |
| 562 // If the host was not in the local cache, this is a new hostname. |
| 563 |
| 564 if (dns_cache_.size() >= kMaxUniqueResolveDnsPerExec) { |
| 565 // Safety net for scripts with unexpectedly many DNS calls. |
| 566 // We will continue running to completion, but will fail every |
| 567 // subsequent DNS request. |
| 568 return false; |
| 569 } |
| 570 |
| 571 bool unused; |
| 572 origin_loop_->PostTask( |
| 573 FROM_HERE, base::Bind(&Job::DoDnsOperation, this, host, op, &unused)); |
| 574 |
| 575 // Wait for the DNS operation to be completed by the host resolver on the |
| 576 // origin thread. After waking up, either the request was cancelled, or |
| 577 // the DNS result is now available in the cache. |
| 578 event_.Wait(); |
| 579 event_.Reset(); |
| 580 |
| 581 if (cancelled_.IsSet()) |
| 582 return false; |
| 583 |
| 584 CHECK(GetDnsFromLocalCache(host, op, output, &rv)); |
| 585 return rv; |
| 586 } |
| 587 |
| 588 bool ProxyResolverV8Tracing::Job::ResolveDnsNonBlocking(const std::string& host, |
| 589 ResolveDnsOperation op, |
| 590 std::string* output) { |
| 591 CheckIsOnWorkerThread(); |
| 592 |
| 593 if (abandoned_) { |
| 594 // If this execution was already abandoned can fail right away. Only 1 DNS |
| 595 // dependency will be traced at a time (for more predictable outcomes). |
| 596 return false; |
| 597 } |
| 598 |
| 599 num_dns_ += 1; |
| 600 |
| 601 // Check if the DNS result for this host has already been cached. |
| 602 bool rv; |
| 603 if (GetDnsFromLocalCache(host, op, output, &rv)) { |
| 604 // Yay, cache hit! |
| 605 return rv; |
| 606 } |
| 607 |
| 608 // If the host was not in the local cache, then this is a new hostname. |
| 609 |
| 610 if (num_dns_ <= last_num_dns_) { |
| 611 // The sequence of DNS operations is different from last time! |
| 612 ScheduleRestartWithBlockingDns(); |
| 613 return false; |
| 614 } |
| 615 |
| 616 if (dns_cache_.size() >= kMaxUniqueResolveDnsPerExec) { |
| 617 // Safety net for scripts with unexpectedly many DNS calls. |
| 618 return false; |
| 619 } |
| 620 |
| 621 DCHECK(!should_restart_with_blocking_dns_); |
| 622 |
| 623 // Post the DNS request to the origin thread. |
| 624 bool resolver_cache_hit = false; |
| 625 origin_loop_->PostTask( |
| 626 FROM_HERE, base::Bind(&Job::DoDnsOperation, this, host, op, |
| 627 &resolver_cache_hit)); |
| 628 |
| 629 // As an optimization to avoid restarting too often, wait until the |
| 630 // resolver's cache has been inspected on the origin thread. |
| 631 event_.Wait(); |
| 632 event_.Reset(); |
| 633 |
| 634 if (cancelled_.IsSet()) |
| 635 return false; |
| 636 |
| 637 if (resolver_cache_hit) { |
| 638 CHECK(GetDnsFromLocalCache(host, op, output, &rv)); |
| 639 return rv; |
| 640 } |
| 641 |
| 642 // Otherwise if the result was not in the cache, then a DNS request has |
| 643 // been started. Abandon this invocation of FindProxyForURL(), it will be |
| 644 // restarted once the DNS request completes. |
| 645 abandoned_ = true; |
| 646 last_num_dns_ = num_dns_; |
| 647 return false; |
| 648 } |
| 649 |
| 650 void ProxyResolverV8Tracing::Job::DoDnsOperation( |
| 651 const std::string& host, ResolveDnsOperation op, bool* out_cache_hit) { |
| 652 CheckIsOnOriginThread(); |
| 653 DCHECK(!pending_dns_); |
| 654 |
| 655 if (cancelled_.IsSet()) |
| 656 return; |
| 657 |
| 658 int result = host_resolver()->Resolve( |
| 659 MakeDnsRequestInfo(host, op), |
| 660 &pending_dns_addresses_, |
| 661 base::Bind(&Job::OnDnsOperationComplete, this), |
| 662 &pending_dns_, |
| 663 bound_net_log_); |
| 664 |
| 665 bool completed_synchronously = result != ERR_IO_PENDING; |
| 666 |
| 667 if (!blocking_dns_) { |
| 668 // Check if the DNS result can be serviced directly from the cache. |
| 669 // (The worker thread is blocked waiting for this information). |
| 670 if (completed_synchronously) { |
| 671 SaveDnsToLocalCache(host, op, result, pending_dns_addresses_); |
| 672 pending_dns_ = NULL; |
| 673 } |
| 674 |
| 675 // Important: Do not read/write |out_cache_hit| after signalling, since |
| 676 // the memory may no longer be valid. |
| 677 *out_cache_hit = completed_synchronously; |
| 678 event_.Signal(); |
| 679 |
| 680 if (completed_synchronously) |
| 681 return; |
| 682 } |
| 683 |
| 684 pending_dns_host_ = host; |
| 685 pending_dns_op_ = op; |
| 686 |
| 687 if (completed_synchronously) |
| 688 OnDnsOperationComplete(result); |
| 689 } |
| 690 |
| 691 void ProxyResolverV8Tracing::Job::OnDnsOperationComplete(int result) { |
| 692 CheckIsOnOriginThread(); |
| 693 |
| 694 DCHECK(pending_dns_); |
| 695 DCHECK(!cancelled_.IsSet()); |
| 696 |
| 697 SaveDnsToLocalCache(pending_dns_host_, pending_dns_op_, result, |
| 698 pending_dns_addresses_); |
| 699 pending_dns_ = NULL; |
| 700 |
| 701 if (!blocking_dns_) { |
| 702 // Restart. This time it should make more progress due to having |
| 703 // cached items. |
| 704 worker_loop()->PostTask(FROM_HERE, |
| 705 base::Bind(&Job::ExecuteNonBlocking, this)); |
| 706 } else { |
| 707 // Otherwise wakeup the blocked worker thread. |
| 708 event_.Signal(); |
| 709 } |
| 710 } |
| 711 |
| 712 void ProxyResolverV8Tracing::Job::ScheduleRestartWithBlockingDns() { |
| 713 CheckIsOnWorkerThread(); |
| 714 |
| 715 DCHECK(!should_restart_with_blocking_dns_); |
| 716 DCHECK(!abandoned_); |
| 717 DCHECK(!blocking_dns_); |
| 718 |
| 719 abandoned_ = true; |
| 720 |
| 721 // The restart will happen after ExecuteNonBlocking() finishes. |
| 722 should_restart_with_blocking_dns_ = true; |
| 723 } |
| 724 |
| 725 bool ProxyResolverV8Tracing::Job::GetDnsFromLocalCache( |
| 726 const std::string& host, |
| 727 ResolveDnsOperation op, |
| 728 std::string* output, |
| 729 bool* return_value) { |
| 730 CheckIsOnWorkerThread(); |
| 731 |
| 732 DnsCache::const_iterator it = dns_cache_.find(MakeDnsCacheKey(host, op)); |
| 733 if (it == dns_cache_.end()) |
| 734 return false; |
| 735 |
| 736 *output = it->second; |
| 737 *return_value = !it->second.empty(); |
| 738 return true; |
| 739 } |
| 740 |
| 741 void ProxyResolverV8Tracing::Job::SaveDnsToLocalCache( |
| 742 const std::string& host, |
| 743 ResolveDnsOperation op, |
| 744 int net_error, |
| 745 const net::AddressList& addresses) { |
| 746 CheckIsOnOriginThread(); |
| 747 |
| 748 // Serialize the result into a string to save to the cache. |
| 749 std::string cache_value; |
| 750 if (net_error != OK) { |
| 751 cache_value = std::string(); |
| 752 } else if (op == DNS_RESOLVE || op == MY_IP_ADDRESS) { |
| 753 // dnsResolve() and myIpAddress() are expected to return a single IP |
| 754 // address. |
| 755 cache_value = addresses.front().ToStringWithoutPort(); |
| 756 } else { |
| 757 // The *Ex versions are expected to return a semi-colon separated list. |
| 758 for (AddressList::const_iterator iter = addresses.begin(); |
| 759 iter != addresses.end(); ++iter) { |
| 760 if (!cache_value.empty()) |
| 761 cache_value += ";"; |
| 762 cache_value += iter->ToStringWithoutPort(); |
| 763 } |
| 764 } |
| 765 |
| 766 dns_cache_[MakeDnsCacheKey(host, op)] = cache_value; |
| 767 } |
| 768 |
| 769 // static |
| 770 HostResolver::RequestInfo ProxyResolverV8Tracing::Job::MakeDnsRequestInfo( |
| 771 const std::string& host, ResolveDnsOperation op) { |
| 772 HostPortPair host_port = HostPortPair(host, 80); |
| 773 if (op == MY_IP_ADDRESS || op == MY_IP_ADDRESS_EX) { |
| 774 host_port.set_host(GetHostName()); |
| 775 } |
| 776 |
| 777 HostResolver::RequestInfo info(host_port); |
| 778 |
| 779 // The non-ex flavors are limited to IPv4 results. |
| 780 if (op == MY_IP_ADDRESS || op == DNS_RESOLVE) { |
| 781 info.set_address_family(ADDRESS_FAMILY_IPV4); |
| 782 } |
| 783 |
| 784 return info; |
| 785 } |
| 786 |
| 787 std::string ProxyResolverV8Tracing::Job::MakeDnsCacheKey( |
| 788 const std::string& host, ResolveDnsOperation op) { |
| 789 return StringPrintf("%d:%s", op, host.c_str()); |
| 790 } |
| 791 |
| 792 void ProxyResolverV8Tracing::Job::HandleAlertOrError(bool is_alert, |
| 793 int line_number, |
| 794 const string16& message) { |
| 795 CheckIsOnWorkerThread(); |
| 796 |
| 797 if (cancelled_.IsSet()) |
| 798 return; |
| 799 |
| 800 if (blocking_dns_) { |
| 801 // In blocking DNS mode the events can be dispatched immediately. |
| 802 DispatchAlertOrError(is_alert, line_number, message); |
| 803 return; |
| 804 } |
| 805 |
| 806 // Otherwise in nonblocking mode, buffer all the messages until |
| 807 // the end. |
| 808 |
| 809 if (abandoned_) |
| 810 return; |
| 811 |
| 812 alerts_and_errors_byte_cost_ += sizeof(AlertOrError) + message.size() * 2; |
| 813 |
| 814 // If there have been lots of messages, enqueing could be expensive on |
| 815 // memory. Consider a script which does megabytes worth of alerts(). |
| 816 // Avoid this by falling back to blocking mode. |
| 817 if (alerts_and_errors_byte_cost_ > kMaxAlertsAndErrorsBytes) { |
| 818 ScheduleRestartWithBlockingDns(); |
| 819 return; |
| 820 } |
| 821 |
| 822 AlertOrError entry = {is_alert, line_number, message}; |
| 823 alerts_and_errors_.push_back(entry); |
| 824 } |
| 825 |
| 826 void ProxyResolverV8Tracing::Job::DispatchBufferedAlertsAndErrors() { |
| 827 CheckIsOnWorkerThread(); |
| 828 DCHECK(!blocking_dns_); |
| 829 DCHECK(!abandoned_); |
| 830 |
| 831 for (size_t i = 0; i < alerts_and_errors_.size(); ++i) { |
| 832 const AlertOrError& x = alerts_and_errors_[i]; |
| 833 DispatchAlertOrError(x.is_alert, x.line_number, x.message); |
| 834 } |
| 835 } |
| 836 |
| 837 void ProxyResolverV8Tracing::Job::DispatchAlertOrError( |
| 838 bool is_alert, int line_number, const string16& message) { |
| 839 CheckIsOnWorkerThread(); |
| 840 |
| 841 // Note that the handling of cancellation is racy with regard to |
| 842 // alerts/errors. The request might get cancelled shortly after this |
| 843 // check! (There is no lock being held to guarantee otherwise). |
| 844 // |
| 845 // If this happens, then some information will get written to the NetLog |
| 846 // needlessly, however the NetLog will still be alive so it shouldn't cause |
| 847 // problems. |
| 848 if (cancelled_.IsSet()) |
| 849 return; |
| 850 |
| 851 if (is_alert) { |
| 852 // ------------------- |
| 853 // alert |
| 854 // ------------------- |
| 855 VLOG(1) << "PAC-alert: " << message; |
| 856 |
| 857 // Send to the NetLog. |
| 858 LogEventToCurrentRequestAndGlobally( |
| 859 NetLog::TYPE_PAC_JAVASCRIPT_ALERT, |
| 860 NetLog::StringCallback("message", &message)); |
| 861 } else { |
| 862 // ------------------- |
| 863 // error |
| 864 // ------------------- |
| 865 if (line_number == -1) |
| 866 VLOG(1) << "PAC-error: " << message; |
| 867 else |
| 868 VLOG(1) << "PAC-error: " << "line: " << line_number << ": " << message; |
| 869 |
| 870 // Send the error to the NetLog. |
| 871 LogEventToCurrentRequestAndGlobally( |
| 872 NetLog::TYPE_PAC_JAVASCRIPT_ERROR, |
| 873 base::Bind(&NetLogErrorCallback, line_number, &message)); |
| 874 |
| 875 if (error_observer()) |
| 876 error_observer()->OnPACScriptError(line_number, message); |
| 877 } |
| 878 } |
| 879 |
| 880 void ProxyResolverV8Tracing::Job::LogEventToCurrentRequestAndGlobally( |
| 881 NetLog::EventType type, |
| 882 const NetLog::ParametersCallback& parameters_callback) { |
| 883 CheckIsOnWorkerThread(); |
| 884 bound_net_log_.AddEvent(type, parameters_callback); |
| 885 |
| 886 // Emit to the global NetLog event stream. |
| 887 if (net_log()) |
| 888 net_log()->AddGlobalEntry(type, parameters_callback); |
| 889 } |
| 890 |
| 891 ProxyResolverV8Tracing::ProxyResolverV8Tracing( |
| 892 HostResolver* host_resolver, |
| 893 ProxyResolverErrorObserver* error_observer, |
| 894 NetLog* net_log) |
| 895 : ProxyResolver(true /*expects_pac_bytes*/), |
| 896 host_resolver_(host_resolver), |
| 897 error_observer_(error_observer), |
| 898 net_log_(net_log), |
| 899 num_outstanding_callbacks_(0) { |
| 900 DCHECK(host_resolver); |
| 901 // Start up the thread. |
| 902 thread_.reset(new base::Thread("Proxy resolver")); |
| 903 CHECK(thread_->Start()); |
| 904 |
| 905 v8_resolver_.reset(new ProxyResolverV8); |
| 906 } |
| 907 |
| 908 ProxyResolverV8Tracing::~ProxyResolverV8Tracing() { |
| 909 // Note, all requests should have been cancelled. |
| 910 CHECK(!set_pac_script_job_); |
| 911 CHECK_EQ(0, num_outstanding_callbacks_); |
| 912 |
| 913 // Join the worker thread. |
| 914 // See http://crbug.com/69710. |
| 915 base::ThreadRestrictions::ScopedAllowIO allow_io; |
| 916 thread_.reset(); |
| 917 } |
| 918 |
| 919 int ProxyResolverV8Tracing::GetProxyForURL(const GURL& url, |
| 920 ProxyInfo* results, |
| 921 const CompletionCallback& callback, |
| 922 RequestHandle* request, |
| 923 const BoundNetLog& net_log) { |
| 924 DCHECK(CalledOnValidThread()); |
| 925 DCHECK(!callback.is_null()); |
| 926 DCHECK(!set_pac_script_job_); |
| 927 |
| 928 scoped_refptr<Job> job = new Job(this); |
| 929 |
| 930 if (request) |
| 931 *request = job.get(); |
| 932 |
| 933 job->StartGetProxyForURL(url, results, net_log, callback); |
| 934 return ERR_IO_PENDING; |
| 935 } |
| 936 |
| 937 void ProxyResolverV8Tracing::CancelRequest(RequestHandle request) { |
| 938 Job* job = reinterpret_cast<Job*>(request); |
| 939 job->Cancel(); |
| 940 } |
| 941 |
| 942 LoadState ProxyResolverV8Tracing::GetLoadState(RequestHandle request) const { |
| 943 Job* job = reinterpret_cast<Job*>(request); |
| 944 return job->GetLoadState(); |
| 945 } |
| 946 |
| 947 void ProxyResolverV8Tracing::CancelSetPacScript() { |
| 948 DCHECK(set_pac_script_job_); |
| 949 set_pac_script_job_->Cancel(); |
| 950 set_pac_script_job_ = NULL; |
| 951 } |
| 952 |
| 953 void ProxyResolverV8Tracing::PurgeMemory() { |
| 954 thread_->message_loop()->PostTask( |
| 955 FROM_HERE, |
| 956 base::Bind(&ProxyResolverV8::PurgeMemory, |
| 957 // The use of unretained is safe, since the worker thread |
| 958 // cannot outlive |this|. |
| 959 base::Unretained(v8_resolver_.get()))); |
| 960 } |
| 961 |
| 962 int ProxyResolverV8Tracing::SetPacScript( |
| 963 const scoped_refptr<ProxyResolverScriptData>& script_data, |
| 964 const CompletionCallback& callback) { |
| 965 DCHECK(CalledOnValidThread()); |
| 966 DCHECK(!callback.is_null()); |
| 967 |
| 968 // Note that there should not be any outstanding (non-cancelled) Jobs when |
| 969 // setting the PAC script (ProxyService should guarantee this). If there are, |
| 970 // then they might complete in strange ways after the new script is set. |
| 971 DCHECK(!set_pac_script_job_); |
| 972 CHECK_EQ(0, num_outstanding_callbacks_); |
| 973 |
| 974 set_pac_script_job_ = new Job(this); |
| 975 set_pac_script_job_->StartSetPacScript(script_data, callback); |
| 976 |
| 977 return ERR_IO_PENDING; |
| 978 } |
| 979 |
| 980 } // namespace net |
OLD | NEW |