Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(437)

Side by Side Diff: chrome/browser/extensions/api/web_request/web_request_api.cc

Issue 568583002: Introduce WebRequestEventRouterDelegate. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Hide tab_id and window_id from extensions. Created 6 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/extensions/api/web_request/web_request_api.h" 5 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/bind_helpers.h" 10 #include "base/bind_helpers.h"
11 #include "base/json/json_writer.h" 11 #include "base/json/json_writer.h"
12 #include "base/lazy_instance.h" 12 #include "base/lazy_instance.h"
13 #include "base/metrics/histogram.h" 13 #include "base/metrics/histogram.h"
14 #include "base/strings/string_number_conversions.h" 14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h" 15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h" 16 #include "base/strings/utf_string_conversions.h"
17 #include "base/time/time.h" 17 #include "base/time/time.h"
18 #include "base/values.h" 18 #include "base/values.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/chrome_content_browser_client.h"
21 #include "chrome/browser/extensions/activity_log/activity_action_constants.h"
22 #include "chrome/browser/extensions/activity_log/activity_actions.h"
23 #include "chrome/browser/extensions/activity_log/activity_log.h"
24 #include "chrome/browser/extensions/activity_log/web_request_constants.h"
25 #include "chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_ registry.h" 19 #include "chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_ registry.h"
26 #include "chrome/browser/extensions/api/web_request/upload_data_presenter.h" 20 #include "chrome/browser/extensions/api/web_request/upload_data_presenter.h"
27 #include "chrome/browser/extensions/api/web_request/web_request_api_helpers.h" 21 #include "chrome/browser/extensions/api/web_request/web_request_api_helpers.h"
28 #include "chrome/browser/extensions/api/web_request/web_request_time_tracker.h" 22 #include "chrome/browser/extensions/api/web_request/web_request_time_tracker.h"
29 #include "chrome/browser/extensions/extension_renderer_state.h"
30 #include "chrome/browser/profiles/profile.h"
31 #include "chrome/browser/profiles/profile_manager.h"
32 #include "chrome/common/extensions/api/web_request.h" 23 #include "chrome/common/extensions/api/web_request.h"
33 #include "chrome/common/extensions/extension_constants.h"
34 #include "chrome/common/url_constants.h"
35 #include "chrome/grit/generated_resources.h"
36 #include "content/public/browser/browser_message_filter.h" 24 #include "content/public/browser/browser_message_filter.h"
37 #include "content/public/browser/browser_thread.h" 25 #include "content/public/browser/browser_thread.h"
38 #include "content/public/browser/render_frame_host.h" 26 #include "content/public/browser/render_frame_host.h"
39 #include "content/public/browser/render_process_host.h" 27 #include "content/public/browser/render_process_host.h"
40 #include "content/public/browser/resource_request_info.h" 28 #include "content/public/browser/resource_request_info.h"
41 #include "content/public/browser/user_metrics.h" 29 #include "content/public/browser/user_metrics.h"
42 #include "extensions/browser/api/declarative_webrequest/request_stage.h" 30 #include "extensions/browser/api/declarative_webrequest/request_stage.h"
43 #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" 31 #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
32 #include "extensions/browser/api/extensions_api_client.h"
44 #include "extensions/browser/api/web_request/web_request_api_constants.h" 33 #include "extensions/browser/api/web_request/web_request_api_constants.h"
45 #include "extensions/browser/api/web_request/web_request_api_utils.h" 34 #include "extensions/browser/api/web_request/web_request_api_utils.h"
35 #include "extensions/browser/api/web_request/web_request_api_utils.h"
36 #include "extensions/browser/api/web_request/web_request_event_router_delegate.h "
46 #include "extensions/browser/event_router.h" 37 #include "extensions/browser/event_router.h"
47 #include "extensions/browser/extension_message_filter.h" 38 #include "extensions/browser/extension_message_filter.h"
48 #include "extensions/browser/extension_prefs.h" 39 #include "extensions/browser/extension_prefs.h"
49 #include "extensions/browser/extension_registry.h" 40 #include "extensions/browser/extension_registry.h"
50 #include "extensions/browser/extension_system.h" 41 #include "extensions/browser/extension_system.h"
42 #include "extensions/browser/extensions_browser_client.h"
51 #include "extensions/browser/guest_view/web_view/web_view_constants.h" 43 #include "extensions/browser/guest_view/web_view/web_view_constants.h"
52 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h" 44 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
53 #include "extensions/browser/info_map.h" 45 #include "extensions/browser/info_map.h"
54 #include "extensions/browser/runtime_data.h" 46 #include "extensions/browser/runtime_data.h"
55 #include "extensions/browser/warning_service.h" 47 #include "extensions/browser/warning_service.h"
56 #include "extensions/browser/warning_set.h" 48 #include "extensions/browser/warning_set.h"
57 #include "extensions/common/error_utils.h" 49 #include "extensions/common/error_utils.h"
58 #include "extensions/common/event_filtering_info.h" 50 #include "extensions/common/event_filtering_info.h"
59 #include "extensions/common/extension.h" 51 #include "extensions/common/extension.h"
60 #include "extensions/common/extension_messages.h" 52 #include "extensions/common/extension_messages.h"
61 #include "extensions/common/extension_set.h" 53 #include "extensions/common/extension_set.h"
62 #include "extensions/common/features/feature.h" 54 #include "extensions/common/features/feature.h"
63 #include "extensions/common/permissions/permissions_data.h" 55 #include "extensions/common/permissions/permissions_data.h"
64 #include "extensions/common/url_pattern.h" 56 #include "extensions/common/url_pattern.h"
57 #include "extensions/strings/grit/extensions_strings.h"
65 #include "net/base/auth.h" 58 #include "net/base/auth.h"
66 #include "net/base/net_errors.h" 59 #include "net/base/net_errors.h"
67 #include "net/base/upload_data_stream.h" 60 #include "net/base/upload_data_stream.h"
68 #include "net/http/http_response_headers.h" 61 #include "net/http/http_response_headers.h"
69 #include "net/http/http_util.h" 62 #include "net/http/http_util.h"
70 #include "net/url_request/url_request.h" 63 #include "net/url_request/url_request.h"
71 #include "ui/base/l10n/l10n_util.h" 64 #include "ui/base/l10n/l10n_util.h"
72 #include "url/gurl.h" 65 #include "url/gurl.h"
73 66
74 using base::DictionaryValue; 67 using base::DictionaryValue;
(...skipping 10 matching lines...) Expand all
85 using extensions::RulesRegistryService; 78 using extensions::RulesRegistryService;
86 using extensions::Warning; 79 using extensions::Warning;
87 using extensions::WarningService; 80 using extensions::WarningService;
88 using extensions::WarningSet; 81 using extensions::WarningSet;
89 82
90 namespace helpers = extension_web_request_api_helpers; 83 namespace helpers = extension_web_request_api_helpers;
91 namespace utils = extension_web_request_api_utils; 84 namespace utils = extension_web_request_api_utils;
92 namespace keys = extension_web_request_api_constants; 85 namespace keys = extension_web_request_api_constants;
93 namespace web_request = extensions::api::web_request; 86 namespace web_request = extensions::api::web_request;
94 namespace declarative_keys = extensions::declarative_webrequest_constants; 87 namespace declarative_keys = extensions::declarative_webrequest_constants;
95 namespace activitylog = activity_log_web_request_constants;
96 88
97 namespace { 89 namespace {
98 90
99 const char kWebRequestEventPrefix[] = "webRequest."; 91 const char kWebRequestEventPrefix[] = "webRequest.";
100 92
101 // List of all the webRequest events. 93 // List of all the webRequest events.
102 const char* const kWebRequestEvents[] = { 94 const char* const kWebRequestEvents[] = {
103 keys::kOnBeforeRedirectEvent, 95 keys::kOnBeforeRedirectEvent,
104 web_request::OnBeforeRequest::kEventName, 96 web_request::OnBeforeRequest::kEventName,
105 keys::kOnBeforeSendHeadersEvent, 97 keys::kOnBeforeSendHeadersEvent,
106 keys::kOnCompletedEvent, 98 keys::kOnCompletedEvent,
107 web_request::OnErrorOccurred::kEventName, 99 web_request::OnErrorOccurred::kEventName,
108 keys::kOnSendHeadersEvent, 100 keys::kOnSendHeadersEvent,
109 keys::kOnAuthRequiredEvent, 101 keys::kOnAuthRequiredEvent,
110 keys::kOnResponseStartedEvent, 102 keys::kOnResponseStartedEvent,
111 keys::kOnHeadersReceivedEvent, 103 keys::kOnHeadersReceivedEvent,
112 }; 104 };
113 105
114 #define ARRAYEND(array) (array + arraysize(array))
115
116 const char* GetRequestStageAsString( 106 const char* GetRequestStageAsString(
117 ExtensionWebRequestEventRouter::EventTypes type) { 107 ExtensionWebRequestEventRouter::EventTypes type) {
118 switch (type) { 108 switch (type) {
119 case ExtensionWebRequestEventRouter::kInvalidEvent: 109 case ExtensionWebRequestEventRouter::kInvalidEvent:
120 return "Invalid"; 110 return "Invalid";
121 case ExtensionWebRequestEventRouter::kOnBeforeRequest: 111 case ExtensionWebRequestEventRouter::kOnBeforeRequest:
122 return keys::kOnBeforeRequest; 112 return keys::kOnBeforeRequest;
123 case ExtensionWebRequestEventRouter::kOnBeforeSendHeaders: 113 case ExtensionWebRequestEventRouter::kOnBeforeSendHeaders:
124 return keys::kOnBeforeSendHeaders; 114 return keys::kOnBeforeSendHeaders;
125 case ExtensionWebRequestEventRouter::kOnSendHeaders: 115 case ExtensionWebRequestEventRouter::kOnSendHeaders:
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
196 ExtractRequestRoutingInfo(request, &render_process_host_id, &routing_id); 186 ExtractRequestRoutingInfo(request, &render_process_host_id, &routing_id);
197 return extensions::WebViewRendererState::GetInstance()-> 187 return extensions::WebViewRendererState::GetInstance()->
198 GetInfo(render_process_host_id, routing_id, web_view_info); 188 GetInfo(render_process_host_id, routing_id, web_view_info);
199 } 189 }
200 190
201 void ExtractRequestInfoDetails(net::URLRequest* request, 191 void ExtractRequestInfoDetails(net::URLRequest* request,
202 bool* is_main_frame, 192 bool* is_main_frame,
203 int* frame_id, 193 int* frame_id,
204 bool* parent_is_main_frame, 194 bool* parent_is_main_frame,
205 int* parent_frame_id, 195 int* parent_frame_id,
206 int* tab_id,
207 int* window_id,
208 int* render_process_host_id, 196 int* render_process_host_id,
209 int* routing_id, 197 int* routing_id,
210 ResourceType* resource_type) { 198 ResourceType* resource_type) {
211 if (!request->GetUserData(NULL)) 199 if (!request->GetUserData(NULL))
212 return; 200 return;
213 201
214 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); 202 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
215 ExtensionRendererState::GetInstance()->GetTabAndWindowId(
216 info, tab_id, window_id);
217 *frame_id = info->GetRenderFrameID(); 203 *frame_id = info->GetRenderFrameID();
218 *is_main_frame = info->IsMainFrame(); 204 *is_main_frame = info->IsMainFrame();
219 *parent_frame_id = info->GetParentRenderFrameID(); 205 *parent_frame_id = info->GetParentRenderFrameID();
220 *parent_is_main_frame = info->ParentIsMainFrame(); 206 *parent_is_main_frame = info->ParentIsMainFrame();
221 *render_process_host_id = info->GetChildID(); 207 *render_process_host_id = info->GetChildID();
222 *routing_id = info->GetRouteID(); 208 *routing_id = info->GetRouteID();
223
224 // Restrict the resource type to the values we care about. 209 // Restrict the resource type to the values we care about.
225 if (utils::IsRelevantResourceType(info->GetResourceType())) 210 if (utils::IsRelevantResourceType(info->GetResourceType()))
226 *resource_type = info->GetResourceType(); 211 *resource_type = info->GetResourceType();
227 else 212 else
228 *resource_type = content::RESOURCE_TYPE_LAST_TYPE; 213 *resource_type = content::RESOURCE_TYPE_LAST_TYPE;
229 } 214 }
230 215
231 // Extracts from |request| information for the keys requestId, url, method,
232 // frameId, tabId, type, and timeStamp and writes these into |out| to be passed
233 // on to extensions.
234 void ExtractRequestInfo(net::URLRequest* request, base::DictionaryValue* out) {
235 bool is_main_frame = false;
236 int frame_id = -1;
237 bool parent_is_main_frame = false;
238 int parent_frame_id = -1;
239 int frame_id_for_extension = -1;
240 int parent_frame_id_for_extension = -1;
241 int tab_id = -1;
242 int window_id = -1;
243 int render_process_host_id = -1;
244 int routing_id = -1;
245 ResourceType resource_type = content::RESOURCE_TYPE_LAST_TYPE;
246 ExtractRequestInfoDetails(request, &is_main_frame, &frame_id,
247 &parent_is_main_frame, &parent_frame_id, &tab_id,
248 &window_id, &render_process_host_id, &routing_id,
249 &resource_type);
250 frame_id_for_extension = GetFrameId(is_main_frame, frame_id);
251 parent_frame_id_for_extension = GetFrameId(parent_is_main_frame,
252 parent_frame_id);
253
254 out->SetString(keys::kRequestIdKey,
255 base::Uint64ToString(request->identifier()));
256 out->SetString(keys::kUrlKey, request->url().spec());
257 out->SetString(keys::kMethodKey, request->method());
258 out->SetInteger(keys::kFrameIdKey, frame_id_for_extension);
259 out->SetInteger(keys::kParentFrameIdKey, parent_frame_id_for_extension);
260 out->SetInteger(keys::kTabIdKey, tab_id);
261 out->SetString(keys::kTypeKey, utils::ResourceTypeToString(resource_type));
262 out->SetDouble(keys::kTimeStampKey, base::Time::Now().ToDoubleT() * 1000);
263 }
264
265 // Extracts the body from |request| and writes the data into |out|. 216 // Extracts the body from |request| and writes the data into |out|.
266 void ExtractRequestInfoBody(const net::URLRequest* request, 217 void ExtractRequestInfoBody(const net::URLRequest* request,
267 base::DictionaryValue* out) { 218 base::DictionaryValue* out) {
268 const net::UploadDataStream* upload_data = request->get_upload(); 219 const net::UploadDataStream* upload_data = request->get_upload();
269 if (!upload_data || 220 if (!upload_data ||
270 (request->method() != "POST" && request->method() != "PUT")) 221 (request->method() != "POST" && request->method() != "PUT"))
271 return; // Need to exit without "out->Set(keys::kRequestBodyKey, ...);" . 222 return; // Need to exit without "out->Set(keys::kRequestBodyKey, ...);" .
272 223
273 base::DictionaryValue* requestBody = new base::DictionaryValue(); 224 base::DictionaryValue* requestBody = new base::DictionaryValue();
274 out->Set(keys::kRequestBodyKey, requestBody); 225 out->Set(keys::kRequestBodyKey, requestBody);
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
324 if (!header_value->HasKey(keys::kHeaderBinaryValueKey)) { 275 if (!header_value->HasKey(keys::kHeaderBinaryValueKey)) {
325 *value = ""; 276 *value = "";
326 } else if (!header_value->GetList(keys::kHeaderBinaryValueKey, &list) || 277 } else if (!header_value->GetList(keys::kHeaderBinaryValueKey, &list) ||
327 !helpers::CharListToString(list, value)) { 278 !helpers::CharListToString(list, value)) {
328 return false; 279 return false;
329 } 280 }
330 } 281 }
331 return true; 282 return true;
332 } 283 }
333 284
334 // Converts the |name|, |value| pair of a http header to a HttpHeaders
335 // dictionary. Ownership is passed to the caller.
336 base::DictionaryValue* ToHeaderDictionary(const std::string& name,
337 const std::string& value) {
338 base::DictionaryValue* header = new base::DictionaryValue();
339 header->SetString(keys::kHeaderNameKey, name);
340 if (base::IsStringUTF8(value)) {
341 header->SetString(keys::kHeaderValueKey, value);
342 } else {
343 header->Set(keys::kHeaderBinaryValueKey,
344 helpers::StringToCharList(value));
345 }
346 return header;
347 }
348
349 // Creates a list of HttpHeaders (see the extension API JSON). If |headers| is 285 // Creates a list of HttpHeaders (see the extension API JSON). If |headers| is
350 // NULL, the list is empty. Ownership is passed to the caller. 286 // NULL, the list is empty. Ownership is passed to the caller.
351 base::ListValue* GetResponseHeadersList( 287 base::ListValue* GetResponseHeadersList(
352 const net::HttpResponseHeaders* headers) { 288 const net::HttpResponseHeaders* headers) {
353 base::ListValue* headers_value = new base::ListValue(); 289 base::ListValue* headers_value = new base::ListValue();
354 if (headers) { 290 if (headers) {
355 void* iter = NULL; 291 void* iter = NULL;
356 std::string name; 292 std::string name;
357 std::string value; 293 std::string value;
358 while (headers->EnumerateHeaderLines(&iter, &name, &value)) 294 while (headers->EnumerateHeaderLines(&iter, &name, &value))
359 headers_value->Append(ToHeaderDictionary(name, value)); 295 headers_value->Append(helpers::ToHeaderDictionary(name, value));
360 } 296 }
361 return headers_value; 297 return headers_value;
362 } 298 }
363 299
364 base::ListValue* GetRequestHeadersList(const net::HttpRequestHeaders& headers) { 300 base::ListValue* GetRequestHeadersList(const net::HttpRequestHeaders& headers) {
365 base::ListValue* headers_value = new base::ListValue(); 301 base::ListValue* headers_value = new base::ListValue();
366 for (net::HttpRequestHeaders::Iterator it(headers); it.GetNext(); ) 302 for (net::HttpRequestHeaders::Iterator it(headers); it.GetNext(); )
367 headers_value->Append(ToHeaderDictionary(it.name(), it.value())); 303 headers_value->Append(helpers::ToHeaderDictionary(it.name(), it.value()));
368 return headers_value; 304 return headers_value;
369 } 305 }
370 306
371 // Creates a base::StringValue with the status line of |headers|. If |headers| 307 // Creates a base::StringValue with the status line of |headers|. If |headers|
372 // is NULL, an empty string is returned. Ownership is passed to the caller. 308 // is NULL, an empty string is returned. Ownership is passed to the caller.
373 base::StringValue* GetStatusLine(net::HttpResponseHeaders* headers) { 309 base::StringValue* GetStatusLine(net::HttpResponseHeaders* headers) {
374 return new base::StringValue( 310 return new base::StringValue(
375 headers ? headers->GetStatusLine() : std::string()); 311 headers ? headers->GetStatusLine() : std::string());
376 } 312 }
377 313
378 void RemoveEventListenerOnUI( 314 void RemoveEventListenerOnUI(
379 void* profile_id, 315 void* browser_context_id,
380 const std::string& event_name, 316 const std::string& event_name,
381 int process_id, 317 int process_id,
382 const std::string& extension_id) { 318 const std::string& extension_id) {
383 DCHECK_CURRENTLY_ON(BrowserThread::UI); 319 DCHECK_CURRENTLY_ON(BrowserThread::UI);
384 320
385 Profile* profile = reinterpret_cast<Profile*>(profile_id); 321 content::BrowserContext* browser_context =
386 if (!g_browser_process->profile_manager()->IsValidProfile(profile)) 322 reinterpret_cast<content::BrowserContext*>(browser_context_id);
323 if (!extensions::ExtensionsBrowserClient::Get()->IsValidContext(
324 browser_context))
387 return; 325 return;
388 326
389 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile); 327 extensions::EventRouter* event_router =
328 extensions::EventRouter::Get(browser_context);
390 if (!event_router) 329 if (!event_router)
391 return; 330 return;
392 331
393 content::RenderProcessHost* process = 332 content::RenderProcessHost* process =
394 content::RenderProcessHost::FromID(process_id); 333 content::RenderProcessHost::FromID(process_id);
395 if (!process) 334 if (!process)
396 return; 335 return;
397 336
398 event_router->RemoveEventListener(event_name, process, extension_id); 337 event_router->RemoveEventListener(event_name, process, extension_id);
399 } 338 }
400 339
401 // Sends an event to subscribers of chrome.declarativeWebRequest.onMessage or 340 // Sends an event to subscribers of chrome.declarativeWebRequest.onMessage or
402 // to subscribers of webview.onMessage if the action is being operated upon 341 // to subscribers of webview.onMessage if the action is being operated upon
403 // a <webview> guest renderer. 342 // a <webview> guest renderer.
404 // |extension_id| identifies the extension that sends and receives the event. 343 // |extension_id| identifies the extension that sends and receives the event.
405 // |is_web_view_guest| indicates whether the action is for a <webview>. 344 // |is_web_view_guest| indicates whether the action is for a <webview>.
406 // |web_view_info| is a struct containing information about the <webview> 345 // |web_view_info| is a struct containing information about the <webview>
407 // embedder. 346 // embedder.
408 // |event_argument| is passed to the event listener. 347 // |event_argument| is passed to the event listener.
409 void SendOnMessageEventOnUI( 348 void SendOnMessageEventOnUI(
410 void* profile_id, 349 void* browser_context_id,
411 const std::string& extension_id, 350 const std::string& extension_id,
412 bool is_web_view_guest, 351 bool is_web_view_guest,
413 const extensions::WebViewRendererState::WebViewInfo& web_view_info, 352 const extensions::WebViewRendererState::WebViewInfo& web_view_info,
414 scoped_ptr<base::DictionaryValue> event_argument) { 353 scoped_ptr<base::DictionaryValue> event_argument) {
415 DCHECK_CURRENTLY_ON(BrowserThread::UI); 354 DCHECK_CURRENTLY_ON(BrowserThread::UI);
416 355
417 Profile* profile = reinterpret_cast<Profile*>(profile_id); 356 content::BrowserContext* browser_context =
418 if (!g_browser_process->profile_manager()->IsValidProfile(profile)) 357 reinterpret_cast<content::BrowserContext*>(browser_context_id);
358 if (!extensions::ExtensionsBrowserClient::Get()->IsValidContext(
359 browser_context))
419 return; 360 return;
420 361
421 scoped_ptr<base::ListValue> event_args(new base::ListValue); 362 scoped_ptr<base::ListValue> event_args(new base::ListValue);
422 event_args->Append(event_argument.release()); 363 event_args->Append(event_argument.release());
423 364
424 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile); 365 extensions::EventRouter* event_router =
366 extensions::EventRouter::Get(browser_context);
425 367
426 extensions::EventFilteringInfo event_filtering_info; 368 extensions::EventFilteringInfo event_filtering_info;
427 369
428 std::string event_name; 370 std::string event_name;
429 // The instance ID uniquely identifies a <webview> instance within an embedder 371 // The instance ID uniquely identifies a <webview> instance within an embedder
430 // process. We use a filter here so that only event listeners for a particular 372 // process. We use a filter here so that only event listeners for a particular
431 // <webview> will fire. 373 // <webview> will fire.
432 if (is_web_view_guest) { 374 if (is_web_view_guest) {
433 event_filtering_info.SetInstanceID(web_view_info.instance_id); 375 event_filtering_info.SetInstanceID(web_view_info.instance_id);
434 event_name = webview::kEventMessage; 376 event_name = webview::kEventMessage;
435 } else { 377 } else {
436 event_name = declarative_keys::kOnMessage; 378 event_name = declarative_keys::kOnMessage;
437 } 379 }
438 380
439 scoped_ptr<extensions::Event> event(new extensions::Event( 381 scoped_ptr<extensions::Event> event(new extensions::Event(
440 event_name, 382 event_name,
441 event_args.Pass(), profile, GURL(), 383 event_args.Pass(), browser_context, GURL(),
442 extensions::EventRouter::USER_GESTURE_UNKNOWN, 384 extensions::EventRouter::USER_GESTURE_UNKNOWN,
443 event_filtering_info)); 385 event_filtering_info));
444 event_router->DispatchEventToExtension(extension_id, event.Pass()); 386 event_router->DispatchEventToExtension(extension_id, event.Pass());
445 } 387 }
446 388
447 void RemoveEventListenerOnIOThread( 389 void RemoveEventListenerOnIOThread(
448 content::BrowserContext* browser_context, 390 content::BrowserContext* browser_context,
449 const std::string& extension_id, 391 const std::string& extension_id,
450 const std::string& sub_event_name) { 392 const std::string& sub_event_name) {
451 ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener( 393 ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(
(...skipping 174 matching lines...) Expand 10 before | Expand all | Expand 10 after
626 if (!it.value().GetAsList(&types_value)) 568 if (!it.value().GetAsList(&types_value))
627 return false; 569 return false;
628 for (size_t i = 0; i < types_value->GetSize(); ++i) { 570 for (size_t i = 0; i < types_value->GetSize(); ++i) {
629 std::string type_str; 571 std::string type_str;
630 ResourceType type; 572 ResourceType type;
631 if (!types_value->GetString(i, &type_str) || 573 if (!types_value->GetString(i, &type_str) ||
632 !utils::ParseResourceType(type_str, &type)) 574 !utils::ParseResourceType(type_str, &type))
633 return false; 575 return false;
634 types.push_back(type); 576 types.push_back(type);
635 } 577 }
636 } else if (it.key() == "tabId") { 578 } else if (it.key() == "extraRequestParams") {
Fady Samuel 2014/09/18 16:34:44 Pass to delegate here.
637 if (!it.value().GetAsInteger(&tab_id)) 579 const base::DictionaryValue* params_value = NULL;
580 if (!it.value().GetAsDictionary(&params_value))
638 return false; 581 return false;
639 } else if (it.key() == "windowId") { 582 if (!extra_request_params->OnInitFromValueCheck(*params_value))
640 if (!it.value().GetAsInteger(&window_id))
641 return false; 583 return false;
642 } else { 584 } else {
643 return false; 585 return false;
644 } 586 }
645 } 587 }
646 return true; 588 return true;
647 } 589 }
648 590
649 // static 591 // static
650 bool ExtensionWebRequestEventRouter::ExtraInfoSpec::InitFromValue( 592 bool ExtensionWebRequestEventRouter::ExtraInfoSpec::InitFromValue(
(...skipping 28 matching lines...) Expand all
679 ExtensionWebRequestEventRouter::EventResponse::EventResponse( 621 ExtensionWebRequestEventRouter::EventResponse::EventResponse(
680 const std::string& extension_id, const base::Time& extension_install_time) 622 const std::string& extension_id, const base::Time& extension_install_time)
681 : extension_id(extension_id), 623 : extension_id(extension_id),
682 extension_install_time(extension_install_time), 624 extension_install_time(extension_install_time),
683 cancel(false) { 625 cancel(false) {
684 } 626 }
685 627
686 ExtensionWebRequestEventRouter::EventResponse::~EventResponse() { 628 ExtensionWebRequestEventRouter::EventResponse::~EventResponse() {
687 } 629 }
688 630
631 ExtensionWebRequestEventRouter::RequestFilter::RequestFilter()
632 : extra_request_params(
633 extensions::ExtensionsAPIClient::Get()->CreateExtraRequestParams()) {
634 }
689 635
690 ExtensionWebRequestEventRouter::RequestFilter::RequestFilter() 636
691 : tab_id(-1), window_id(-1) { 637 ExtensionWebRequestEventRouter::RequestFilter::RequestFilter(
638 const ExtensionWebRequestEventRouter::RequestFilter& filter)
639 : extra_request_params(new ExtraRequestParams(
640 *(filter.extra_request_params.get()))) {
692 } 641 }
693 642
694 ExtensionWebRequestEventRouter::RequestFilter::~RequestFilter() { 643 ExtensionWebRequestEventRouter::RequestFilter::~RequestFilter() {
695 } 644 }
696 645
646 ExtensionWebRequestEventRouter::RequestFilter&
647 ExtensionWebRequestEventRouter::RequestFilter::operator=(
648 const ExtensionWebRequestEventRouter::RequestFilter& filter) {
649 extra_request_params.reset(new ExtraRequestParams(
650 *(filter.extra_request_params.get())));
651 return *this;
652 }
653
697 // 654 //
698 // ExtensionWebRequestEventRouter 655 // ExtensionWebRequestEventRouter
699 // 656 //
700 657
701 // static 658 // static
702 ExtensionWebRequestEventRouter* ExtensionWebRequestEventRouter::GetInstance() { 659 ExtensionWebRequestEventRouter* ExtensionWebRequestEventRouter::GetInstance() {
703 return Singleton<ExtensionWebRequestEventRouter>::get(); 660 return Singleton<ExtensionWebRequestEventRouter>::get();
704 } 661 }
705 662
706 ExtensionWebRequestEventRouter::ExtensionWebRequestEventRouter() 663 ExtensionWebRequestEventRouter::ExtensionWebRequestEventRouter()
707 : request_time_tracker_(new ExtensionWebRequestTimeTracker) { 664 : request_time_tracker_(new ExtensionWebRequestTimeTracker) {
665 web_request_event_router_delegate_.reset(
666 extensions::ExtensionsAPIClient::Get()->
667 CreateWebRequestEventRouterDelegate());
708 } 668 }
709 669
710 ExtensionWebRequestEventRouter::~ExtensionWebRequestEventRouter() { 670 ExtensionWebRequestEventRouter::~ExtensionWebRequestEventRouter() {
711 } 671 }
712 672
713 void ExtensionWebRequestEventRouter::RegisterRulesRegistry( 673 void ExtensionWebRequestEventRouter::RegisterRulesRegistry(
714 void* profile, 674 void* browser_context,
715 const RulesRegistryService::WebViewKey& webview_key, 675 const RulesRegistryService::WebViewKey& webview_key,
716 scoped_refptr<extensions::WebRequestRulesRegistry> rules_registry) { 676 scoped_refptr<extensions::WebRequestRulesRegistry> rules_registry) {
717 RulesRegistryKey key(profile, webview_key); 677 RulesRegistryKey key(browser_context, webview_key);
718 if (rules_registry.get()) 678 if (rules_registry.get())
719 rules_registries_[key] = rules_registry; 679 rules_registries_[key] = rules_registry;
720 else 680 else
721 rules_registries_.erase(key); 681 rules_registries_.erase(key);
722 } 682 }
723 683
684 void ExtensionWebRequestEventRouter::ExtractRequestInfo(
685 net::URLRequest* request, base::DictionaryValue* out) {
686 bool is_main_frame = false;
687 int frame_id = -1;
688 bool parent_is_main_frame = false;
689 int parent_frame_id = -1;
690 int frame_id_for_extension = -1;
691 int parent_frame_id_for_extension = -1;
692 int render_process_host_id = -1;
693 int routing_id = -1;
694 ResourceType resource_type = content::RESOURCE_TYPE_LAST_TYPE;
695 ExtractRequestInfoDetails(request, &is_main_frame, &frame_id,
696 &parent_is_main_frame, &parent_frame_id,
697 &render_process_host_id, &routing_id,
698 &resource_type);
699 frame_id_for_extension = GetFrameId(is_main_frame, frame_id);
700 parent_frame_id_for_extension = GetFrameId(parent_is_main_frame,
701 parent_frame_id);
702
703 out->SetString(keys::kRequestIdKey,
704 base::Uint64ToString(request->identifier()));
705 out->SetString(keys::kUrlKey, request->url().spec());
706 out->SetString(keys::kMethodKey, request->method());
707 out->SetInteger(keys::kFrameIdKey, frame_id_for_extension);
708 out->SetInteger(keys::kParentFrameIdKey, parent_frame_id_for_extension);
709 out->SetString(keys::kTypeKey, utils::ResourceTypeToString(resource_type));
710 out->SetDouble(keys::kTimeStampKey, base::Time::Now().ToDoubleT() * 1000);
711 if (web_request_event_router_delegate_) {
712 web_request_event_router_delegate_->ExtractExtraRequestDetails(
713 request, out);
714 }
715 }
716
724 int ExtensionWebRequestEventRouter::OnBeforeRequest( 717 int ExtensionWebRequestEventRouter::OnBeforeRequest(
725 void* profile, 718 void* browser_context,
726 InfoMap* extension_info_map, 719 InfoMap* extension_info_map,
727 net::URLRequest* request, 720 net::URLRequest* request,
728 const net::CompletionCallback& callback, 721 const net::CompletionCallback& callback,
729 GURL* new_url) { 722 GURL* new_url) {
730 // We hide events from the system context as well as sensitive requests. 723 // We hide events from the system context as well as sensitive requests.
731 if (!profile || 724 if (!browser_context ||
732 WebRequestPermissions::HideRequest(extension_info_map, request)) 725 WebRequestPermissions::HideRequest(extension_info_map, request))
733 return net::OK; 726 return net::OK;
734 727
735 if (IsPageLoad(request)) 728 if (IsPageLoad(request))
736 NotifyPageLoad(); 729 NotifyPageLoad();
737 730
738 request_time_tracker_->LogRequestStartTime(request->identifier(), 731 request_time_tracker_->LogRequestStartTime(request->identifier(),
739 base::Time::Now(), 732 base::Time::Now(),
740 request->url(), 733 request->url(),
741 profile); 734 browser_context);
742 735
743 // Whether to initialized blocked_requests_. 736 // Whether to initialized blocked_requests_.
744 bool initialize_blocked_requests = false; 737 bool initialize_blocked_requests = false;
745 738
746 initialize_blocked_requests |= 739 initialize_blocked_requests |=
747 ProcessDeclarativeRules(profile, extension_info_map, 740 ProcessDeclarativeRules(browser_context, extension_info_map,
748 web_request::OnBeforeRequest::kEventName, request, 741 web_request::OnBeforeRequest::kEventName, request,
749 extensions::ON_BEFORE_REQUEST, NULL); 742 extensions::ON_BEFORE_REQUEST, NULL);
750 743
751 int extra_info_spec = 0; 744 int extra_info_spec = 0;
752 std::vector<const EventListener*> listeners = 745 std::vector<const EventListener*> listeners =
753 GetMatchingListeners(profile, extension_info_map, 746 GetMatchingListeners(browser_context, extension_info_map,
754 web_request::OnBeforeRequest::kEventName, request, 747 web_request::OnBeforeRequest::kEventName, request,
755 &extra_info_spec); 748 &extra_info_spec);
756 if (!listeners.empty() && 749 if (!listeners.empty() &&
757 !GetAndSetSignaled(request->identifier(), kOnBeforeRequest)) { 750 !GetAndSetSignaled(request->identifier(), kOnBeforeRequest)) {
758 base::ListValue args; 751 base::ListValue args;
759 base::DictionaryValue* dict = new base::DictionaryValue(); 752 base::DictionaryValue* dict = new base::DictionaryValue();
760 ExtractRequestInfo(request, dict); 753 ExtractRequestInfo(request, dict);
761 if (extra_info_spec & ExtraInfoSpec::REQUEST_BODY) 754 if (extra_info_spec & ExtraInfoSpec::REQUEST_BODY)
762 ExtractRequestInfoBody(request, dict); 755 ExtractRequestInfoBody(request, dict);
763 args.Append(dict); 756 args.Append(dict);
764 757
765 initialize_blocked_requests |= 758 initialize_blocked_requests |=
766 DispatchEvent(profile, request, listeners, args); 759 DispatchEvent(browser_context, request, listeners, args);
767 } 760 }
768 761
769 if (!initialize_blocked_requests) 762 if (!initialize_blocked_requests)
770 return net::OK; // Nobody saw a reason for modifying the request. 763 return net::OK; // Nobody saw a reason for modifying the request.
771 764
772 blocked_requests_[request->identifier()].event = kOnBeforeRequest; 765 blocked_requests_[request->identifier()].event = kOnBeforeRequest;
773 blocked_requests_[request->identifier()].is_incognito |= 766 blocked_requests_[request->identifier()].is_incognito |=
774 IsIncognitoProfile(profile); 767 IsIncognitoBrowserContext(browser_context);
775 blocked_requests_[request->identifier()].request = request; 768 blocked_requests_[request->identifier()].request = request;
776 blocked_requests_[request->identifier()].callback = callback; 769 blocked_requests_[request->identifier()].callback = callback;
777 blocked_requests_[request->identifier()].new_url = new_url; 770 blocked_requests_[request->identifier()].new_url = new_url;
778 blocked_requests_[request->identifier()].net_log = &request->net_log(); 771 blocked_requests_[request->identifier()].net_log = &request->net_log();
779 772
780 if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) { 773 if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) {
781 // If there are no blocking handlers, only the declarative rules tried 774 // If there are no blocking handlers, only the declarative rules tried
782 // to modify the request and we can respond synchronously. 775 // to modify the request and we can respond synchronously.
783 return ExecuteDeltas(profile, request->identifier(), 776 return ExecuteDeltas(browser_context, request->identifier(),
784 false /* call_callback*/); 777 false /* call_callback*/);
785 } else { 778 } else {
786 return net::ERR_IO_PENDING; 779 return net::ERR_IO_PENDING;
787 } 780 }
788 } 781 }
789 782
790 int ExtensionWebRequestEventRouter::OnBeforeSendHeaders( 783 int ExtensionWebRequestEventRouter::OnBeforeSendHeaders(
791 void* profile, 784 void* browser_context,
792 InfoMap* extension_info_map, 785 InfoMap* extension_info_map,
793 net::URLRequest* request, 786 net::URLRequest* request,
794 const net::CompletionCallback& callback, 787 const net::CompletionCallback& callback,
795 net::HttpRequestHeaders* headers) { 788 net::HttpRequestHeaders* headers) {
796 // We hide events from the system context as well as sensitive requests. 789 // We hide events from the system context as well as sensitive requests.
797 if (!profile || 790 if (!browser_context ||
798 WebRequestPermissions::HideRequest(extension_info_map, request)) 791 WebRequestPermissions::HideRequest(extension_info_map, request))
799 return net::OK; 792 return net::OK;
800 793
801 bool initialize_blocked_requests = false; 794 bool initialize_blocked_requests = false;
802 795
803 initialize_blocked_requests |= 796 initialize_blocked_requests |=
804 ProcessDeclarativeRules(profile, extension_info_map, 797 ProcessDeclarativeRules(browser_context, extension_info_map,
805 keys::kOnBeforeSendHeadersEvent, request, 798 keys::kOnBeforeSendHeadersEvent, request,
806 extensions::ON_BEFORE_SEND_HEADERS, NULL); 799 extensions::ON_BEFORE_SEND_HEADERS, NULL);
807 800
808 int extra_info_spec = 0; 801 int extra_info_spec = 0;
809 std::vector<const EventListener*> listeners = 802 std::vector<const EventListener*> listeners =
810 GetMatchingListeners(profile, extension_info_map, 803 GetMatchingListeners(browser_context, extension_info_map,
811 keys::kOnBeforeSendHeadersEvent, request, 804 keys::kOnBeforeSendHeadersEvent, request,
812 &extra_info_spec); 805 &extra_info_spec);
813 if (!listeners.empty() && 806 if (!listeners.empty() &&
814 !GetAndSetSignaled(request->identifier(), kOnBeforeSendHeaders)) { 807 !GetAndSetSignaled(request->identifier(), kOnBeforeSendHeaders)) {
815 base::ListValue args; 808 base::ListValue args;
816 base::DictionaryValue* dict = new base::DictionaryValue(); 809 base::DictionaryValue* dict = new base::DictionaryValue();
817 ExtractRequestInfo(request, dict); 810 ExtractRequestInfo(request, dict);
818 if (extra_info_spec & ExtraInfoSpec::REQUEST_HEADERS) 811 if (extra_info_spec & ExtraInfoSpec::REQUEST_HEADERS)
819 dict->Set(keys::kRequestHeadersKey, GetRequestHeadersList(*headers)); 812 dict->Set(keys::kRequestHeadersKey, GetRequestHeadersList(*headers));
820 args.Append(dict); 813 args.Append(dict);
821 814
822 initialize_blocked_requests |= 815 initialize_blocked_requests |=
823 DispatchEvent(profile, request, listeners, args); 816 DispatchEvent(browser_context, request, listeners, args);
824 } 817 }
825 818
826 if (!initialize_blocked_requests) 819 if (!initialize_blocked_requests)
827 return net::OK; // Nobody saw a reason for modifying the request. 820 return net::OK; // Nobody saw a reason for modifying the request.
828 821
829 blocked_requests_[request->identifier()].event = kOnBeforeSendHeaders; 822 blocked_requests_[request->identifier()].event = kOnBeforeSendHeaders;
830 blocked_requests_[request->identifier()].is_incognito |= 823 blocked_requests_[request->identifier()].is_incognito |=
831 IsIncognitoProfile(profile); 824 IsIncognitoBrowserContext(browser_context);
832 blocked_requests_[request->identifier()].request = request; 825 blocked_requests_[request->identifier()].request = request;
833 blocked_requests_[request->identifier()].callback = callback; 826 blocked_requests_[request->identifier()].callback = callback;
834 blocked_requests_[request->identifier()].request_headers = headers; 827 blocked_requests_[request->identifier()].request_headers = headers;
835 blocked_requests_[request->identifier()].net_log = &request->net_log(); 828 blocked_requests_[request->identifier()].net_log = &request->net_log();
836 829
837 if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) { 830 if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) {
838 // If there are no blocking handlers, only the declarative rules tried 831 // If there are no blocking handlers, only the declarative rules tried
839 // to modify the request and we can respond synchronously. 832 // to modify the request and we can respond synchronously.
840 return ExecuteDeltas(profile, request->identifier(), 833 return ExecuteDeltas(browser_context, request->identifier(),
841 false /* call_callback*/); 834 false /* call_callback*/);
842 } else { 835 } else {
843 return net::ERR_IO_PENDING; 836 return net::ERR_IO_PENDING;
844 } 837 }
845 } 838 }
846 839
847 void ExtensionWebRequestEventRouter::OnSendHeaders( 840 void ExtensionWebRequestEventRouter::OnSendHeaders(
848 void* profile, 841 void* browser_context,
849 InfoMap* extension_info_map, 842 InfoMap* extension_info_map,
850 net::URLRequest* request, 843 net::URLRequest* request,
851 const net::HttpRequestHeaders& headers) { 844 const net::HttpRequestHeaders& headers) {
852 // We hide events from the system context as well as sensitive requests. 845 // We hide events from the system context as well as sensitive requests.
853 if (!profile || 846 if (!browser_context ||
854 WebRequestPermissions::HideRequest(extension_info_map, request)) 847 WebRequestPermissions::HideRequest(extension_info_map, request))
855 return; 848 return;
856 849
857 if (GetAndSetSignaled(request->identifier(), kOnSendHeaders)) 850 if (GetAndSetSignaled(request->identifier(), kOnSendHeaders))
858 return; 851 return;
859 852
860 ClearSignaled(request->identifier(), kOnBeforeRedirect); 853 ClearSignaled(request->identifier(), kOnBeforeRedirect);
861 854
862 int extra_info_spec = 0; 855 int extra_info_spec = 0;
863 std::vector<const EventListener*> listeners = 856 std::vector<const EventListener*> listeners =
864 GetMatchingListeners(profile, extension_info_map, 857 GetMatchingListeners(browser_context, extension_info_map,
865 keys::kOnSendHeadersEvent, request, 858 keys::kOnSendHeadersEvent, request,
866 &extra_info_spec); 859 &extra_info_spec);
867 if (listeners.empty()) 860 if (listeners.empty())
868 return; 861 return;
869 862
870 base::ListValue args; 863 base::ListValue args;
871 base::DictionaryValue* dict = new base::DictionaryValue(); 864 base::DictionaryValue* dict = new base::DictionaryValue();
872 ExtractRequestInfo(request, dict); 865 ExtractRequestInfo(request, dict);
873 if (extra_info_spec & ExtraInfoSpec::REQUEST_HEADERS) 866 if (extra_info_spec & ExtraInfoSpec::REQUEST_HEADERS)
874 dict->Set(keys::kRequestHeadersKey, GetRequestHeadersList(headers)); 867 dict->Set(keys::kRequestHeadersKey, GetRequestHeadersList(headers));
875 args.Append(dict); 868 args.Append(dict);
876 869
877 DispatchEvent(profile, request, listeners, args); 870 DispatchEvent(browser_context, request, listeners, args);
878 } 871 }
879 872
880 int ExtensionWebRequestEventRouter::OnHeadersReceived( 873 int ExtensionWebRequestEventRouter::OnHeadersReceived(
881 void* profile, 874 void* browser_context,
882 InfoMap* extension_info_map, 875 InfoMap* extension_info_map,
883 net::URLRequest* request, 876 net::URLRequest* request,
884 const net::CompletionCallback& callback, 877 const net::CompletionCallback& callback,
885 const net::HttpResponseHeaders* original_response_headers, 878 const net::HttpResponseHeaders* original_response_headers,
886 scoped_refptr<net::HttpResponseHeaders>* override_response_headers, 879 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
887 GURL* allowed_unsafe_redirect_url) { 880 GURL* allowed_unsafe_redirect_url) {
888 // We hide events from the system context as well as sensitive requests. 881 // We hide events from the system context as well as sensitive requests.
889 if (!profile || 882 if (!browser_context ||
890 WebRequestPermissions::HideRequest(extension_info_map, request)) 883 WebRequestPermissions::HideRequest(extension_info_map, request))
891 return net::OK; 884 return net::OK;
892 885
893 bool initialize_blocked_requests = false; 886 bool initialize_blocked_requests = false;
894 887
895 initialize_blocked_requests |= 888 initialize_blocked_requests |=
896 ProcessDeclarativeRules(profile, extension_info_map, 889 ProcessDeclarativeRules(browser_context, extension_info_map,
897 keys::kOnHeadersReceivedEvent, request, 890 keys::kOnHeadersReceivedEvent, request,
898 extensions::ON_HEADERS_RECEIVED, 891 extensions::ON_HEADERS_RECEIVED,
899 original_response_headers); 892 original_response_headers);
900 893
901 int extra_info_spec = 0; 894 int extra_info_spec = 0;
902 std::vector<const EventListener*> listeners = 895 std::vector<const EventListener*> listeners =
903 GetMatchingListeners(profile, extension_info_map, 896 GetMatchingListeners(browser_context, extension_info_map,
904 keys::kOnHeadersReceivedEvent, request, 897 keys::kOnHeadersReceivedEvent, request,
905 &extra_info_spec); 898 &extra_info_spec);
906 899
907 if (!listeners.empty() && 900 if (!listeners.empty() &&
908 !GetAndSetSignaled(request->identifier(), kOnHeadersReceived)) { 901 !GetAndSetSignaled(request->identifier(), kOnHeadersReceived)) {
909 base::ListValue args; 902 base::ListValue args;
910 base::DictionaryValue* dict = new base::DictionaryValue(); 903 base::DictionaryValue* dict = new base::DictionaryValue();
911 ExtractRequestInfo(request, dict); 904 ExtractRequestInfo(request, dict);
912 dict->SetString(keys::kStatusLineKey, 905 dict->SetString(keys::kStatusLineKey,
913 original_response_headers->GetStatusLine()); 906 original_response_headers->GetStatusLine());
914 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { 907 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) {
915 dict->Set(keys::kResponseHeadersKey, 908 dict->Set(keys::kResponseHeadersKey,
916 GetResponseHeadersList(original_response_headers)); 909 GetResponseHeadersList(original_response_headers));
917 } 910 }
918 args.Append(dict); 911 args.Append(dict);
919 912
920 initialize_blocked_requests |= 913 initialize_blocked_requests |=
921 DispatchEvent(profile, request, listeners, args); 914 DispatchEvent(browser_context, request, listeners, args);
922 } 915 }
923 916
924 if (!initialize_blocked_requests) 917 if (!initialize_blocked_requests)
925 return net::OK; // Nobody saw a reason for modifying the request. 918 return net::OK; // Nobody saw a reason for modifying the request.
926 919
927 blocked_requests_[request->identifier()].event = kOnHeadersReceived; 920 blocked_requests_[request->identifier()].event = kOnHeadersReceived;
928 blocked_requests_[request->identifier()].is_incognito |= 921 blocked_requests_[request->identifier()].is_incognito |=
929 IsIncognitoProfile(profile); 922 IsIncognitoBrowserContext(browser_context);
930 blocked_requests_[request->identifier()].request = request; 923 blocked_requests_[request->identifier()].request = request;
931 blocked_requests_[request->identifier()].callback = callback; 924 blocked_requests_[request->identifier()].callback = callback;
932 blocked_requests_[request->identifier()].net_log = &request->net_log(); 925 blocked_requests_[request->identifier()].net_log = &request->net_log();
933 blocked_requests_[request->identifier()].override_response_headers = 926 blocked_requests_[request->identifier()].override_response_headers =
934 override_response_headers; 927 override_response_headers;
935 blocked_requests_[request->identifier()].original_response_headers = 928 blocked_requests_[request->identifier()].original_response_headers =
936 original_response_headers; 929 original_response_headers;
937 blocked_requests_[request->identifier()].new_url = 930 blocked_requests_[request->identifier()].new_url =
938 allowed_unsafe_redirect_url; 931 allowed_unsafe_redirect_url;
939 932
940 if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) { 933 if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) {
941 // If there are no blocking handlers, only the declarative rules tried 934 // If there are no blocking handlers, only the declarative rules tried
942 // to modify the request and we can respond synchronously. 935 // to modify the request and we can respond synchronously.
943 return ExecuteDeltas(profile, request->identifier(), 936 return ExecuteDeltas(browser_context, request->identifier(),
944 false /* call_callback*/); 937 false /* call_callback*/);
945 } else { 938 } else {
946 return net::ERR_IO_PENDING; 939 return net::ERR_IO_PENDING;
947 } 940 }
948 } 941 }
949 942
950 net::NetworkDelegate::AuthRequiredResponse 943 net::NetworkDelegate::AuthRequiredResponse
951 ExtensionWebRequestEventRouter::OnAuthRequired( 944 ExtensionWebRequestEventRouter::OnAuthRequired(
952 void* profile, 945 void* browser_context,
953 InfoMap* extension_info_map, 946 InfoMap* extension_info_map,
954 net::URLRequest* request, 947 net::URLRequest* request,
955 const net::AuthChallengeInfo& auth_info, 948 const net::AuthChallengeInfo& auth_info,
956 const net::NetworkDelegate::AuthCallback& callback, 949 const net::NetworkDelegate::AuthCallback& callback,
957 net::AuthCredentials* credentials) { 950 net::AuthCredentials* credentials) {
958 // No profile means that this is for authentication challenges in the 951 // No browser_context means that this is for authentication challenges in the
959 // system context. Skip in that case. Also skip sensitive requests. 952 // system context. Skip in that case. Also skip sensitive requests.
960 if (!profile || 953 if (!browser_context ||
961 WebRequestPermissions::HideRequest(extension_info_map, request)) 954 WebRequestPermissions::HideRequest(extension_info_map, request))
962 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; 955 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
963 956
964 int extra_info_spec = 0; 957 int extra_info_spec = 0;
965 std::vector<const EventListener*> listeners = 958 std::vector<const EventListener*> listeners =
966 GetMatchingListeners(profile, extension_info_map, 959 GetMatchingListeners(browser_context, extension_info_map,
967 keys::kOnAuthRequiredEvent, request, 960 keys::kOnAuthRequiredEvent, request,
968 &extra_info_spec); 961 &extra_info_spec);
969 if (listeners.empty()) 962 if (listeners.empty())
970 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; 963 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
971 964
972 base::ListValue args; 965 base::ListValue args;
973 base::DictionaryValue* dict = new base::DictionaryValue(); 966 base::DictionaryValue* dict = new base::DictionaryValue();
974 ExtractRequestInfo(request, dict); 967 ExtractRequestInfo(request, dict);
975 dict->SetBoolean(keys::kIsProxyKey, auth_info.is_proxy); 968 dict->SetBoolean(keys::kIsProxyKey, auth_info.is_proxy);
976 if (!auth_info.scheme.empty()) 969 if (!auth_info.scheme.empty())
977 dict->SetString(keys::kSchemeKey, auth_info.scheme); 970 dict->SetString(keys::kSchemeKey, auth_info.scheme);
978 if (!auth_info.realm.empty()) 971 if (!auth_info.realm.empty())
979 dict->SetString(keys::kRealmKey, auth_info.realm); 972 dict->SetString(keys::kRealmKey, auth_info.realm);
980 base::DictionaryValue* challenger = new base::DictionaryValue(); 973 base::DictionaryValue* challenger = new base::DictionaryValue();
981 challenger->SetString(keys::kHostKey, auth_info.challenger.host()); 974 challenger->SetString(keys::kHostKey, auth_info.challenger.host());
982 challenger->SetInteger(keys::kPortKey, auth_info.challenger.port()); 975 challenger->SetInteger(keys::kPortKey, auth_info.challenger.port());
983 dict->Set(keys::kChallengerKey, challenger); 976 dict->Set(keys::kChallengerKey, challenger);
984 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers())); 977 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers()));
985 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { 978 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) {
986 dict->Set(keys::kResponseHeadersKey, 979 dict->Set(keys::kResponseHeadersKey,
987 GetResponseHeadersList(request->response_headers())); 980 GetResponseHeadersList(request->response_headers()));
988 } 981 }
989 args.Append(dict); 982 args.Append(dict);
990 983
991 if (DispatchEvent(profile, request, listeners, args)) { 984 if (DispatchEvent(browser_context, request, listeners, args)) {
992 blocked_requests_[request->identifier()].event = kOnAuthRequired; 985 blocked_requests_[request->identifier()].event = kOnAuthRequired;
993 blocked_requests_[request->identifier()].is_incognito |= 986 blocked_requests_[request->identifier()].is_incognito |=
994 IsIncognitoProfile(profile); 987 IsIncognitoBrowserContext(browser_context);
995 blocked_requests_[request->identifier()].request = request; 988 blocked_requests_[request->identifier()].request = request;
996 blocked_requests_[request->identifier()].auth_callback = callback; 989 blocked_requests_[request->identifier()].auth_callback = callback;
997 blocked_requests_[request->identifier()].auth_credentials = credentials; 990 blocked_requests_[request->identifier()].auth_credentials = credentials;
998 blocked_requests_[request->identifier()].net_log = &request->net_log(); 991 blocked_requests_[request->identifier()].net_log = &request->net_log();
999 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_IO_PENDING; 992 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_IO_PENDING;
1000 } 993 }
1001 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; 994 return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
1002 } 995 }
1003 996
1004 void ExtensionWebRequestEventRouter::OnBeforeRedirect( 997 void ExtensionWebRequestEventRouter::OnBeforeRedirect(
1005 void* profile, 998 void* browser_context,
1006 InfoMap* extension_info_map, 999 InfoMap* extension_info_map,
1007 net::URLRequest* request, 1000 net::URLRequest* request,
1008 const GURL& new_location) { 1001 const GURL& new_location) {
1009 // We hide events from the system context as well as sensitive requests. 1002 // We hide events from the system context as well as sensitive requests.
1010 if (!profile || 1003 if (!browser_context ||
1011 WebRequestPermissions::HideRequest(extension_info_map, request)) 1004 WebRequestPermissions::HideRequest(extension_info_map, request))
1012 return; 1005 return;
1013 1006
1014 if (GetAndSetSignaled(request->identifier(), kOnBeforeRedirect)) 1007 if (GetAndSetSignaled(request->identifier(), kOnBeforeRedirect))
1015 return; 1008 return;
1016 1009
1017 ClearSignaled(request->identifier(), kOnBeforeRequest); 1010 ClearSignaled(request->identifier(), kOnBeforeRequest);
1018 ClearSignaled(request->identifier(), kOnBeforeSendHeaders); 1011 ClearSignaled(request->identifier(), kOnBeforeSendHeaders);
1019 ClearSignaled(request->identifier(), kOnSendHeaders); 1012 ClearSignaled(request->identifier(), kOnSendHeaders);
1020 ClearSignaled(request->identifier(), kOnHeadersReceived); 1013 ClearSignaled(request->identifier(), kOnHeadersReceived);
1021 1014
1022 int extra_info_spec = 0; 1015 int extra_info_spec = 0;
1023 std::vector<const EventListener*> listeners = 1016 std::vector<const EventListener*> listeners =
1024 GetMatchingListeners(profile, extension_info_map, 1017 GetMatchingListeners(browser_context, extension_info_map,
1025 keys::kOnBeforeRedirectEvent, request, 1018 keys::kOnBeforeRedirectEvent, request,
1026 &extra_info_spec); 1019 &extra_info_spec);
1027 if (listeners.empty()) 1020 if (listeners.empty())
1028 return; 1021 return;
1029 1022
1030 int http_status_code = request->GetResponseCode(); 1023 int http_status_code = request->GetResponseCode();
1031 1024
1032 std::string response_ip = request->GetSocketAddress().host(); 1025 std::string response_ip = request->GetSocketAddress().host();
1033 1026
1034 base::ListValue args; 1027 base::ListValue args;
1035 base::DictionaryValue* dict = new base::DictionaryValue(); 1028 base::DictionaryValue* dict = new base::DictionaryValue();
1036 ExtractRequestInfo(request, dict); 1029 ExtractRequestInfo(request, dict);
1037 dict->SetString(keys::kRedirectUrlKey, new_location.spec()); 1030 dict->SetString(keys::kRedirectUrlKey, new_location.spec());
1038 dict->SetInteger(keys::kStatusCodeKey, http_status_code); 1031 dict->SetInteger(keys::kStatusCodeKey, http_status_code);
1039 if (!response_ip.empty()) 1032 if (!response_ip.empty())
1040 dict->SetString(keys::kIpKey, response_ip); 1033 dict->SetString(keys::kIpKey, response_ip);
1041 dict->SetBoolean(keys::kFromCache, request->was_cached()); 1034 dict->SetBoolean(keys::kFromCache, request->was_cached());
1042 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers())); 1035 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers()));
1043 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { 1036 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) {
1044 dict->Set(keys::kResponseHeadersKey, 1037 dict->Set(keys::kResponseHeadersKey,
1045 GetResponseHeadersList(request->response_headers())); 1038 GetResponseHeadersList(request->response_headers()));
1046 } 1039 }
1047 args.Append(dict); 1040 args.Append(dict);
1048 1041
1049 DispatchEvent(profile, request, listeners, args); 1042 DispatchEvent(browser_context, request, listeners, args);
1050 } 1043 }
1051 1044
1052 void ExtensionWebRequestEventRouter::OnResponseStarted( 1045 void ExtensionWebRequestEventRouter::OnResponseStarted(
1053 void* profile, 1046 void* browser_context,
1054 InfoMap* extension_info_map, 1047 InfoMap* extension_info_map,
1055 net::URLRequest* request) { 1048 net::URLRequest* request) {
1056 // We hide events from the system context as well as sensitive requests. 1049 // We hide events from the system context as well as sensitive requests.
1057 if (!profile || 1050 if (!browser_context ||
1058 WebRequestPermissions::HideRequest(extension_info_map, request)) 1051 WebRequestPermissions::HideRequest(extension_info_map, request))
1059 return; 1052 return;
1060 1053
1061 // OnResponseStarted is even triggered, when the request was cancelled. 1054 // OnResponseStarted is even triggered, when the request was cancelled.
1062 if (request->status().status() != net::URLRequestStatus::SUCCESS) 1055 if (request->status().status() != net::URLRequestStatus::SUCCESS)
1063 return; 1056 return;
1064 1057
1065 int extra_info_spec = 0; 1058 int extra_info_spec = 0;
1066 std::vector<const EventListener*> listeners = 1059 std::vector<const EventListener*> listeners =
1067 GetMatchingListeners(profile, extension_info_map, 1060 GetMatchingListeners(browser_context, extension_info_map,
1068 keys::kOnResponseStartedEvent, request, 1061 keys::kOnResponseStartedEvent, request,
1069 &extra_info_spec); 1062 &extra_info_spec);
1070 if (listeners.empty()) 1063 if (listeners.empty())
1071 return; 1064 return;
1072 1065
1073 // UrlRequestFileJobs do not send headers, so we simulate their behavior. 1066 // UrlRequestFileJobs do not send headers, so we simulate their behavior.
1074 int response_code = 200; 1067 int response_code = 200;
1075 if (request->response_headers()) 1068 if (request->response_headers())
1076 response_code = request->response_headers()->response_code(); 1069 response_code = request->response_headers()->response_code();
1077 1070
1078 std::string response_ip = request->GetSocketAddress().host(); 1071 std::string response_ip = request->GetSocketAddress().host();
1079 1072
1080 base::ListValue args; 1073 base::ListValue args;
1081 base::DictionaryValue* dict = new base::DictionaryValue(); 1074 base::DictionaryValue* dict = new base::DictionaryValue();
1082 ExtractRequestInfo(request, dict); 1075 ExtractRequestInfo(request, dict);
1083 if (!response_ip.empty()) 1076 if (!response_ip.empty())
1084 dict->SetString(keys::kIpKey, response_ip); 1077 dict->SetString(keys::kIpKey, response_ip);
1085 dict->SetBoolean(keys::kFromCache, request->was_cached()); 1078 dict->SetBoolean(keys::kFromCache, request->was_cached());
1086 dict->SetInteger(keys::kStatusCodeKey, response_code); 1079 dict->SetInteger(keys::kStatusCodeKey, response_code);
1087 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers())); 1080 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers()));
1088 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { 1081 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) {
1089 dict->Set(keys::kResponseHeadersKey, 1082 dict->Set(keys::kResponseHeadersKey,
1090 GetResponseHeadersList(request->response_headers())); 1083 GetResponseHeadersList(request->response_headers()));
1091 } 1084 }
1092 args.Append(dict); 1085 args.Append(dict);
1093 1086
1094 DispatchEvent(profile, request, listeners, args); 1087 DispatchEvent(browser_context, request, listeners, args);
1095 } 1088 }
1096 1089
1097 void ExtensionWebRequestEventRouter::OnCompleted(void* profile, 1090 void ExtensionWebRequestEventRouter::OnCompleted(void* browser_context,
1098 InfoMap* extension_info_map, 1091 InfoMap* extension_info_map,
1099 net::URLRequest* request) { 1092 net::URLRequest* request) {
1100 // We hide events from the system context as well as sensitive requests. 1093 // We hide events from the system context as well as sensitive requests.
1101 // However, if the request first became sensitive after redirecting we have 1094 // However, if the request first became sensitive after redirecting we have
1102 // already signaled it and thus we have to signal the end of it. This is 1095 // already signaled it and thus we have to signal the end of it. This is
1103 // risk-free because the handler cannot modify the request now. 1096 // risk-free because the handler cannot modify the request now.
1104 if (!profile || 1097 if (!browser_context ||
1105 (WebRequestPermissions::HideRequest(extension_info_map, request) && 1098 (WebRequestPermissions::HideRequest(extension_info_map, request) &&
1106 !WasSignaled(*request))) 1099 !WasSignaled(*request)))
1107 return; 1100 return;
1108 1101
1109 request_time_tracker_->LogRequestEndTime(request->identifier(), 1102 request_time_tracker_->LogRequestEndTime(request->identifier(),
1110 base::Time::Now()); 1103 base::Time::Now());
1111 1104
1112 DCHECK(request->status().status() == net::URLRequestStatus::SUCCESS); 1105 DCHECK(request->status().status() == net::URLRequestStatus::SUCCESS);
1113 1106
1114 DCHECK(!GetAndSetSignaled(request->identifier(), kOnCompleted)); 1107 DCHECK(!GetAndSetSignaled(request->identifier(), kOnCompleted));
1115 1108
1116 ClearPendingCallbacks(request); 1109 ClearPendingCallbacks(request);
1117 1110
1118 int extra_info_spec = 0; 1111 int extra_info_spec = 0;
1119 std::vector<const EventListener*> listeners = 1112 std::vector<const EventListener*> listeners =
1120 GetMatchingListeners(profile, extension_info_map, 1113 GetMatchingListeners(browser_context, extension_info_map,
1121 keys::kOnCompletedEvent, request, &extra_info_spec); 1114 keys::kOnCompletedEvent, request, &extra_info_spec);
1122 if (listeners.empty()) 1115 if (listeners.empty())
1123 return; 1116 return;
1124 1117
1125 // UrlRequestFileJobs do not send headers, so we simulate their behavior. 1118 // UrlRequestFileJobs do not send headers, so we simulate their behavior.
1126 int response_code = 200; 1119 int response_code = 200;
1127 if (request->response_headers()) 1120 if (request->response_headers())
1128 response_code = request->response_headers()->response_code(); 1121 response_code = request->response_headers()->response_code();
1129 1122
1130 std::string response_ip = request->GetSocketAddress().host(); 1123 std::string response_ip = request->GetSocketAddress().host();
1131 1124
1132 base::ListValue args; 1125 base::ListValue args;
1133 base::DictionaryValue* dict = new base::DictionaryValue(); 1126 base::DictionaryValue* dict = new base::DictionaryValue();
1134 ExtractRequestInfo(request, dict); 1127 ExtractRequestInfo(request, dict);
1135 dict->SetInteger(keys::kStatusCodeKey, response_code); 1128 dict->SetInteger(keys::kStatusCodeKey, response_code);
1136 if (!response_ip.empty()) 1129 if (!response_ip.empty())
1137 dict->SetString(keys::kIpKey, response_ip); 1130 dict->SetString(keys::kIpKey, response_ip);
1138 dict->SetBoolean(keys::kFromCache, request->was_cached()); 1131 dict->SetBoolean(keys::kFromCache, request->was_cached());
1139 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers())); 1132 dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers()));
1140 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { 1133 if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) {
1141 dict->Set(keys::kResponseHeadersKey, 1134 dict->Set(keys::kResponseHeadersKey,
1142 GetResponseHeadersList(request->response_headers())); 1135 GetResponseHeadersList(request->response_headers()));
1143 } 1136 }
1144 args.Append(dict); 1137 args.Append(dict);
1145 1138
1146 DispatchEvent(profile, request, listeners, args); 1139 DispatchEvent(browser_context, request, listeners, args);
1147 } 1140 }
1148 1141
1149 void ExtensionWebRequestEventRouter::OnErrorOccurred( 1142 void ExtensionWebRequestEventRouter::OnErrorOccurred(
1150 void* profile, 1143 void* browser_context,
1151 InfoMap* extension_info_map, 1144 InfoMap* extension_info_map,
1152 net::URLRequest* request, 1145 net::URLRequest* request,
1153 bool started) { 1146 bool started) {
1154 // We hide events from the system context as well as sensitive requests. 1147 // We hide events from the system context as well as sensitive requests.
1155 // However, if the request first became sensitive after redirecting we have 1148 // However, if the request first became sensitive after redirecting we have
1156 // already signaled it and thus we have to signal the end of it. This is 1149 // already signaled it and thus we have to signal the end of it. This is
1157 // risk-free because the handler cannot modify the request now. 1150 // risk-free because the handler cannot modify the request now.
1158 if (!profile || 1151 if (!browser_context ||
1159 (WebRequestPermissions::HideRequest(extension_info_map, request) && 1152 (WebRequestPermissions::HideRequest(extension_info_map, request) &&
1160 !WasSignaled(*request))) 1153 !WasSignaled(*request)))
1161 return; 1154 return;
1162 1155
1163 request_time_tracker_->LogRequestEndTime(request->identifier(), 1156 request_time_tracker_->LogRequestEndTime(request->identifier(),
1164 base::Time::Now()); 1157 base::Time::Now());
1165 1158
1166 DCHECK(request->status().status() == net::URLRequestStatus::FAILED || 1159 DCHECK(request->status().status() == net::URLRequestStatus::FAILED ||
1167 request->status().status() == net::URLRequestStatus::CANCELED); 1160 request->status().status() == net::URLRequestStatus::CANCELED);
1168 1161
1169 DCHECK(!GetAndSetSignaled(request->identifier(), kOnErrorOccurred)); 1162 DCHECK(!GetAndSetSignaled(request->identifier(), kOnErrorOccurred));
1170 1163
1171 ClearPendingCallbacks(request); 1164 ClearPendingCallbacks(request);
1172 1165
1173 int extra_info_spec = 0; 1166 int extra_info_spec = 0;
1174 std::vector<const EventListener*> listeners = 1167 std::vector<const EventListener*> listeners =
1175 GetMatchingListeners(profile, extension_info_map, 1168 GetMatchingListeners(browser_context, extension_info_map,
1176 web_request::OnErrorOccurred::kEventName, request, 1169 web_request::OnErrorOccurred::kEventName, request,
1177 &extra_info_spec); 1170 &extra_info_spec);
1178 if (listeners.empty()) 1171 if (listeners.empty())
1179 return; 1172 return;
1180 1173
1181 base::ListValue args; 1174 base::ListValue args;
1182 base::DictionaryValue* dict = new base::DictionaryValue(); 1175 base::DictionaryValue* dict = new base::DictionaryValue();
1183 ExtractRequestInfo(request, dict); 1176 ExtractRequestInfo(request, dict);
1184 if (started) { 1177 if (started) {
1185 std::string response_ip = request->GetSocketAddress().host(); 1178 std::string response_ip = request->GetSocketAddress().host();
1186 if (!response_ip.empty()) 1179 if (!response_ip.empty())
1187 dict->SetString(keys::kIpKey, response_ip); 1180 dict->SetString(keys::kIpKey, response_ip);
1188 } 1181 }
1189 dict->SetBoolean(keys::kFromCache, request->was_cached()); 1182 dict->SetBoolean(keys::kFromCache, request->was_cached());
1190 dict->SetString(keys::kErrorKey, 1183 dict->SetString(keys::kErrorKey,
1191 net::ErrorToString(request->status().error())); 1184 net::ErrorToString(request->status().error()));
1192 args.Append(dict); 1185 args.Append(dict);
1193 1186
1194 DispatchEvent(profile, request, listeners, args); 1187 DispatchEvent(browser_context, request, listeners, args);
1195 } 1188 }
1196 1189
1197 void ExtensionWebRequestEventRouter::OnURLRequestDestroyed( 1190 void ExtensionWebRequestEventRouter::OnURLRequestDestroyed(
1198 void* profile, net::URLRequest* request) { 1191 void* browser_context, net::URLRequest* request) {
1199 ClearPendingCallbacks(request); 1192 ClearPendingCallbacks(request);
1200 1193
1201 signaled_requests_.erase(request->identifier()); 1194 signaled_requests_.erase(request->identifier());
1202 1195
1203 request_time_tracker_->LogRequestEndTime(request->identifier(), 1196 request_time_tracker_->LogRequestEndTime(request->identifier(),
1204 base::Time::Now()); 1197 base::Time::Now());
1205 } 1198 }
1206 1199
1207 void ExtensionWebRequestEventRouter::ClearPendingCallbacks( 1200 void ExtensionWebRequestEventRouter::ClearPendingCallbacks(
1208 net::URLRequest* request) { 1201 net::URLRequest* request) {
1209 blocked_requests_.erase(request->identifier()); 1202 blocked_requests_.erase(request->identifier());
1210 } 1203 }
1211 1204
1212 bool ExtensionWebRequestEventRouter::DispatchEvent( 1205 bool ExtensionWebRequestEventRouter::DispatchEvent(
1213 void* profile_id, 1206 void* browser_context,
1214 net::URLRequest* request, 1207 net::URLRequest* request,
1215 const std::vector<const EventListener*>& listeners, 1208 const std::vector<const EventListener*>& listeners,
1216 const base::ListValue& args) { 1209 const base::ListValue& args) {
1217 // TODO(mpcomplete): Consider consolidating common (extension_id,json_args) 1210 // TODO(mpcomplete): Consider consolidating common (extension_id,json_args)
1218 // pairs into a single message sent to a list of sub_event_names. 1211 // pairs into a single message sent to a list of sub_event_names.
1219 int num_handlers_blocking = 0; 1212 int num_handlers_blocking = 0;
1220 for (std::vector<const EventListener*>::const_iterator it = listeners.begin(); 1213 for (std::vector<const EventListener*>::const_iterator it = listeners.begin();
1221 it != listeners.end(); ++it) { 1214 it != listeners.end(); ++it) {
1222 // Filter out the optional keys that this listener didn't request. 1215 // Filter out the optional keys that this listener didn't request.
1223 scoped_ptr<base::ListValue> args_filtered(args.DeepCopy()); 1216 scoped_ptr<base::ListValue> args_filtered(args.DeepCopy());
1224 base::DictionaryValue* dict = NULL; 1217 base::DictionaryValue* dict = NULL;
1225 CHECK(args_filtered->GetDictionary(0, &dict) && dict); 1218 CHECK(args_filtered->GetDictionary(0, &dict) && dict);
1226 if (!((*it)->extra_info_spec & ExtraInfoSpec::REQUEST_HEADERS)) 1219 if (!((*it)->extra_info_spec & ExtraInfoSpec::REQUEST_HEADERS))
1227 dict->Remove(keys::kRequestHeadersKey, NULL); 1220 dict->Remove(keys::kRequestHeadersKey, NULL);
1228 if (!((*it)->extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS)) 1221 if (!((*it)->extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS))
1229 dict->Remove(keys::kResponseHeadersKey, NULL); 1222 dict->Remove(keys::kResponseHeadersKey, NULL);
1230 1223
1231 extensions::EventRouter::DispatchEvent( 1224 extensions::EventRouter::DispatchEvent(
1232 (*it)->ipc_sender.get(), profile_id, 1225 (*it)->ipc_sender.get(), browser_context,
1233 (*it)->extension_id, (*it)->sub_event_name, 1226 (*it)->extension_id, (*it)->sub_event_name,
1234 args_filtered.Pass(), 1227 args_filtered.Pass(),
1235 extensions::EventRouter::USER_GESTURE_UNKNOWN, 1228 extensions::EventRouter::USER_GESTURE_UNKNOWN,
1236 extensions::EventFilteringInfo()); 1229 extensions::EventFilteringInfo());
1237 if ((*it)->extra_info_spec & 1230 if ((*it)->extra_info_spec &
1238 (ExtraInfoSpec::BLOCKING | ExtraInfoSpec::ASYNC_BLOCKING)) { 1231 (ExtraInfoSpec::BLOCKING | ExtraInfoSpec::ASYNC_BLOCKING)) {
1239 (*it)->blocked_requests.insert(request->identifier()); 1232 (*it)->blocked_requests.insert(request->identifier());
1240 // If this is the first delegate blocking the request, go ahead and log 1233 // If this is the first delegate blocking the request, go ahead and log
1241 // it. 1234 // it.
1242 if (num_handlers_blocking == 0) { 1235 if (num_handlers_blocking == 0) {
1243 std::string delegate_info = 1236 std::string delegate_info =
1244 l10n_util::GetStringFUTF8(IDS_LOAD_STATE_PARAMETER_EXTENSION, 1237 l10n_util::GetStringFUTF8(IDS_LOAD_STATE_PARAMETER_EXTENSION,
1245 base::UTF8ToUTF16((*it)->extension_name)); 1238 base::UTF8ToUTF16((*it)->extension_name));
1246 // LobAndReport allows extensions that block requests to be displayed in 1239 // LobAndReport allows extensions that block requests to be displayed in
1247 // the load status bar. 1240 // the load status bar.
1248 request->LogAndReportBlockedBy(delegate_info.c_str()); 1241 request->LogAndReportBlockedBy(delegate_info.c_str());
1249 } 1242 }
1250 ++num_handlers_blocking; 1243 ++num_handlers_blocking;
1251 } 1244 }
1252 } 1245 }
1253 1246
1254 if (num_handlers_blocking > 0) { 1247 if (num_handlers_blocking > 0) {
1255 blocked_requests_[request->identifier()].request = request; 1248 blocked_requests_[request->identifier()].request = request;
1256 blocked_requests_[request->identifier()].is_incognito |= 1249 blocked_requests_[request->identifier()].is_incognito |=
1257 IsIncognitoProfile(profile_id); 1250 IsIncognitoBrowserContext(browser_context);
1258 blocked_requests_[request->identifier()].num_handlers_blocking += 1251 blocked_requests_[request->identifier()].num_handlers_blocking +=
1259 num_handlers_blocking; 1252 num_handlers_blocking;
1260 blocked_requests_[request->identifier()].blocking_time = base::Time::Now(); 1253 blocked_requests_[request->identifier()].blocking_time = base::Time::Now();
1261 1254
1262 return true; 1255 return true;
1263 } 1256 }
1264 1257
1265 return false; 1258 return false;
1266 } 1259 }
1267 1260
1268 void ExtensionWebRequestEventRouter::OnEventHandled( 1261 void ExtensionWebRequestEventRouter::OnEventHandled(
1269 void* profile, 1262 void* browser_context,
1270 const std::string& extension_id, 1263 const std::string& extension_id,
1271 const std::string& event_name, 1264 const std::string& event_name,
1272 const std::string& sub_event_name, 1265 const std::string& sub_event_name,
1273 uint64 request_id, 1266 uint64 request_id,
1274 EventResponse* response) { 1267 EventResponse* response) {
1275 EventListener listener; 1268 EventListener listener;
1276 listener.extension_id = extension_id; 1269 listener.extension_id = extension_id;
1277 listener.sub_event_name = sub_event_name; 1270 listener.sub_event_name = sub_event_name;
1278 1271
1279 // The listener may have been removed (e.g. due to the process going away) 1272 // The listener may have been removed (e.g. due to the process going away)
1280 // before we got here. 1273 // before we got here.
1281 std::set<EventListener>::iterator found = 1274 std::set<EventListener>::iterator found =
1282 listeners_[profile][event_name].find(listener); 1275 listeners_[browser_context][event_name].find(listener);
1283 if (found != listeners_[profile][event_name].end()) 1276 if (found != listeners_[browser_context][event_name].end())
1284 found->blocked_requests.erase(request_id); 1277 found->blocked_requests.erase(request_id);
1285 1278
1286 DecrementBlockCount(profile, extension_id, event_name, request_id, response); 1279 DecrementBlockCount(
1280 browser_context, extension_id, event_name, request_id, response);
1287 } 1281 }
1288 1282
1289 bool ExtensionWebRequestEventRouter::AddEventListener( 1283 bool ExtensionWebRequestEventRouter::AddEventListener(
1290 void* profile, 1284 void* browser_context,
1291 const std::string& extension_id, 1285 const std::string& extension_id,
1292 const std::string& extension_name, 1286 const std::string& extension_name,
1293 const std::string& event_name, 1287 const std::string& event_name,
1294 const std::string& sub_event_name, 1288 const std::string& sub_event_name,
1295 const RequestFilter& filter, 1289 const RequestFilter& filter,
1296 int extra_info_spec, 1290 int extra_info_spec,
1297 int embedder_process_id, 1291 int embedder_process_id,
1298 int webview_instance_id, 1292 int webview_instance_id,
1299 base::WeakPtr<IPC::Sender> ipc_sender) { 1293 base::WeakPtr<IPC::Sender> ipc_sender) {
1300 if (!IsWebRequestEvent(event_name)) 1294 if (!IsWebRequestEvent(event_name))
1301 return false; 1295 return false;
1302 1296
1303 EventListener listener; 1297 EventListener listener;
1304 listener.extension_id = extension_id; 1298 listener.extension_id = extension_id;
1305 listener.extension_name = extension_name; 1299 listener.extension_name = extension_name;
1306 listener.sub_event_name = sub_event_name; 1300 listener.sub_event_name = sub_event_name;
1307 listener.filter = filter; 1301 listener.filter = filter;
1308 listener.extra_info_spec = extra_info_spec; 1302 listener.extra_info_spec = extra_info_spec;
1309 listener.ipc_sender = ipc_sender; 1303 listener.ipc_sender = ipc_sender;
1310 listener.embedder_process_id = embedder_process_id; 1304 listener.embedder_process_id = embedder_process_id;
1311 listener.webview_instance_id = webview_instance_id; 1305 listener.webview_instance_id = webview_instance_id;
1312 if (listener.webview_instance_id) { 1306 if (listener.webview_instance_id) {
1313 content::RecordAction( 1307 content::RecordAction(
1314 base::UserMetricsAction("WebView.WebRequest.AddListener")); 1308 base::UserMetricsAction("WebView.WebRequest.AddListener"));
1315 } 1309 }
1316 1310
1317 if (listeners_[profile][event_name].count(listener) != 0u) { 1311 if (listeners_[browser_context][event_name].count(listener) != 0u) {
1318 // This is likely an abuse of the API by a malicious extension. 1312 // This is likely an abuse of the API by a malicious extension.
1319 return false; 1313 return false;
1320 } 1314 }
1321 listeners_[profile][event_name].insert(listener); 1315 listeners_[browser_context][event_name].insert(listener);
1322 return true; 1316 return true;
1323 } 1317 }
1324 1318
1325 void ExtensionWebRequestEventRouter::RemoveEventListener( 1319 void ExtensionWebRequestEventRouter::RemoveEventListener(
1326 void* profile, 1320 void* browser_context,
1327 const std::string& extension_id, 1321 const std::string& extension_id,
1328 const std::string& sub_event_name) { 1322 const std::string& sub_event_name) {
1329 std::string event_name = 1323 std::string event_name =
1330 extensions::EventRouter::GetBaseEventName(sub_event_name); 1324 extensions::EventRouter::GetBaseEventName(sub_event_name);
1331 DCHECK(IsWebRequestEvent(event_name)); 1325 DCHECK(IsWebRequestEvent(event_name));
1332 1326
1333 EventListener listener; 1327 EventListener listener;
1334 listener.extension_id = extension_id; 1328 listener.extension_id = extension_id;
1335 listener.sub_event_name = sub_event_name; 1329 listener.sub_event_name = sub_event_name;
1336 1330
1337 // It's possible for AddEventListener to fail asynchronously. In that case, 1331 // It's possible for AddEventListener to fail asynchronously. In that case,
1338 // the renderer believes the listener exists, while the browser does not. 1332 // the renderer believes the listener exists, while the browser does not.
1339 // Ignore a RemoveEventListener in that case. 1333 // Ignore a RemoveEventListener in that case.
1340 std::set<EventListener>::iterator found = 1334 std::set<EventListener>::iterator found =
1341 listeners_[profile][event_name].find(listener); 1335 listeners_[browser_context][event_name].find(listener);
1342 if (found == listeners_[profile][event_name].end()) 1336 if (found == listeners_[browser_context][event_name].end())
1343 return; 1337 return;
1344 1338
1345 CHECK_EQ(listeners_[profile][event_name].count(listener), 1u) << 1339 CHECK_EQ(listeners_[browser_context][event_name].count(listener), 1u) <<
1346 "extension=" << extension_id << " event=" << event_name; 1340 "extension=" << extension_id << " event=" << event_name;
1347 1341
1348 // Unblock any request that this event listener may have been blocking. 1342 // Unblock any request that this event listener may have been blocking.
1349 for (std::set<uint64>::iterator it = found->blocked_requests.begin(); 1343 for (std::set<uint64>::iterator it = found->blocked_requests.begin();
1350 it != found->blocked_requests.end(); ++it) { 1344 it != found->blocked_requests.end(); ++it) {
1351 DecrementBlockCount(profile, extension_id, event_name, *it, NULL); 1345 DecrementBlockCount(browser_context, extension_id, event_name, *it, NULL);
1352 } 1346 }
1353 1347
1354 listeners_[profile][event_name].erase(listener); 1348 listeners_[browser_context][event_name].erase(listener);
1355 1349
1356 helpers::ClearCacheOnNavigation(); 1350 helpers::ClearCacheOnNavigation();
1357 } 1351 }
1358 1352
1359 void ExtensionWebRequestEventRouter::RemoveWebViewEventListeners( 1353 void ExtensionWebRequestEventRouter::RemoveWebViewEventListeners(
1360 void* profile, 1354 void* browser_context,
1361 const std::string& extension_id, 1355 const std::string& extension_id,
1362 int embedder_process_id, 1356 int embedder_process_id,
1363 int webview_instance_id) { 1357 int webview_instance_id) {
1364 // Iterate over all listeners of all WebRequest events to delete 1358 // Iterate over all listeners of all WebRequest events to delete
1365 // any listeners that belong to the provided <webview>. 1359 // any listeners that belong to the provided <webview>.
1366 ListenerMapForProfile& map_for_profile = listeners_[profile]; 1360 ListenerMapForBrowserContext& map_for_browser_context =
1367 for (ListenerMapForProfile::iterator event_iter = map_for_profile.begin(); 1361 listeners_[browser_context];
1368 event_iter != map_for_profile.end(); ++event_iter) { 1362 for (ListenerMapForBrowserContext::iterator event_iter =
1363 map_for_browser_context.begin();
1364 event_iter != map_for_browser_context.end(); ++event_iter) {
1369 std::vector<EventListener> listeners_to_delete; 1365 std::vector<EventListener> listeners_to_delete;
1370 std::set<EventListener>& listeners = event_iter->second; 1366 std::set<EventListener>& listeners = event_iter->second;
1371 for (std::set<EventListener>::iterator listener_iter = listeners.begin(); 1367 for (std::set<EventListener>::iterator listener_iter = listeners.begin();
1372 listener_iter != listeners.end(); ++listener_iter) { 1368 listener_iter != listeners.end(); ++listener_iter) {
1373 const EventListener& listener = *listener_iter; 1369 const EventListener& listener = *listener_iter;
1374 if (listener.embedder_process_id == embedder_process_id && 1370 if (listener.embedder_process_id == embedder_process_id &&
1375 listener.webview_instance_id == webview_instance_id) 1371 listener.webview_instance_id == webview_instance_id)
1376 listeners_to_delete.push_back(listener); 1372 listeners_to_delete.push_back(listener);
1377 } 1373 }
1378 for (size_t i = 0; i < listeners_to_delete.size(); ++i) { 1374 for (size_t i = 0; i < listeners_to_delete.size(); ++i) {
1379 EventListener& listener = listeners_to_delete[i]; 1375 EventListener& listener = listeners_to_delete[i];
1380 content::BrowserThread::PostTask( 1376 content::BrowserThread::PostTask(
1381 content::BrowserThread::UI, 1377 content::BrowserThread::UI,
1382 FROM_HERE, 1378 FROM_HERE,
1383 base::Bind(&RemoveEventListenerOnUI, 1379 base::Bind(&RemoveEventListenerOnUI,
1384 profile, 1380 browser_context,
1385 listener.sub_event_name, 1381 listener.sub_event_name,
1386 embedder_process_id, 1382 embedder_process_id,
1387 extension_id)); 1383 extension_id));
1388 } 1384 }
1389 } 1385 }
1390 } 1386 }
1391 1387
1392 void ExtensionWebRequestEventRouter::OnOTRProfileCreated( 1388 void ExtensionWebRequestEventRouter::OnOTRBrowserContextCreated(
1393 void* original_profile, void* otr_profile) { 1389 void* original_browser_context, void* otr_browser_context) {
1394 cross_profile_map_[original_profile] = std::make_pair(false, otr_profile); 1390 cross_browser_context_map_[original_browser_context] =
1395 cross_profile_map_[otr_profile] = std::make_pair(true, original_profile); 1391 std::make_pair(false, otr_browser_context);
1392 cross_browser_context_map_[otr_browser_context] =
1393 std::make_pair(true, original_browser_context);
1396 } 1394 }
1397 1395
1398 void ExtensionWebRequestEventRouter::OnOTRProfileDestroyed( 1396 void ExtensionWebRequestEventRouter::OnOTRBrowserContextDestroyed(
1399 void* original_profile, void* otr_profile) { 1397 void* original_browser_context, void* otr_browser_context) {
1400 cross_profile_map_.erase(otr_profile); 1398 cross_browser_context_map_.erase(otr_browser_context);
1401 cross_profile_map_.erase(original_profile); 1399 cross_browser_context_map_.erase(original_browser_context);
1402 } 1400 }
1403 1401
1404 void ExtensionWebRequestEventRouter::AddCallbackForPageLoad( 1402 void ExtensionWebRequestEventRouter::AddCallbackForPageLoad(
1405 const base::Closure& callback) { 1403 const base::Closure& callback) {
1406 callbacks_for_page_load_.push_back(callback); 1404 callbacks_for_page_load_.push_back(callback);
1407 } 1405 }
1408 1406
1409 bool ExtensionWebRequestEventRouter::IsPageLoad( 1407 bool ExtensionWebRequestEventRouter::IsPageLoad(
1410 net::URLRequest* request) const { 1408 net::URLRequest* request) const {
1411 bool is_main_frame = false; 1409 bool is_main_frame = false;
1412 int frame_id = -1; 1410 int frame_id = -1;
1413 bool parent_is_main_frame = false; 1411 bool parent_is_main_frame = false;
1414 int parent_frame_id = -1; 1412 int parent_frame_id = -1;
1415 int tab_id = -1;
1416 int window_id = -1;
1417 int render_process_host_id = -1; 1413 int render_process_host_id = -1;
1418 int routing_id = -1; 1414 int routing_id = -1;
1419 ResourceType resource_type = content::RESOURCE_TYPE_LAST_TYPE; 1415 ResourceType resource_type = content::RESOURCE_TYPE_LAST_TYPE;
1420 1416
1421 ExtractRequestInfoDetails(request, &is_main_frame, &frame_id, 1417 ExtractRequestInfoDetails(request, &is_main_frame, &frame_id,
1422 &parent_is_main_frame, &parent_frame_id, 1418 &parent_is_main_frame, &parent_frame_id,
1423 &tab_id, &window_id, &render_process_host_id, 1419 &render_process_host_id,
1424 &routing_id, &resource_type); 1420 &routing_id, &resource_type);
1425 1421
1426 return resource_type == content::RESOURCE_TYPE_MAIN_FRAME; 1422 return resource_type == content::RESOURCE_TYPE_MAIN_FRAME;
1427 } 1423 }
1428 1424
1429 void ExtensionWebRequestEventRouter::NotifyPageLoad() { 1425 void ExtensionWebRequestEventRouter::NotifyPageLoad() {
1430 for (CallbacksForPageLoad::const_iterator i = 1426 for (CallbacksForPageLoad::const_iterator i =
1431 callbacks_for_page_load_.begin(); 1427 callbacks_for_page_load_.begin();
1432 i != callbacks_for_page_load_.end(); ++i) { 1428 i != callbacks_for_page_load_.end(); ++i) {
1433 i->Run(); 1429 i->Run();
1434 } 1430 }
1435 callbacks_for_page_load_.clear(); 1431 callbacks_for_page_load_.clear();
1436 } 1432 }
1437 1433
1438 void* ExtensionWebRequestEventRouter::GetCrossProfile(void* profile) const { 1434 void* ExtensionWebRequestEventRouter::GetCrossBrowserContext(
1439 CrossProfileMap::const_iterator cross_profile = 1435 void* browser_context) const {
1440 cross_profile_map_.find(profile); 1436 CrossBrowserContextMap::const_iterator cross_browser_context =
1441 if (cross_profile == cross_profile_map_.end()) 1437 cross_browser_context_map_.find(browser_context);
1438 if (cross_browser_context == cross_browser_context_map_.end())
1442 return NULL; 1439 return NULL;
1443 return cross_profile->second.second; 1440 return cross_browser_context->second.second;
1444 } 1441 }
1445 1442
1446 bool ExtensionWebRequestEventRouter::IsIncognitoProfile(void* profile) const { 1443 bool ExtensionWebRequestEventRouter::IsIncognitoBrowserContext(
1447 CrossProfileMap::const_iterator cross_profile = 1444 void* browser_context) const {
1448 cross_profile_map_.find(profile); 1445 CrossBrowserContextMap::const_iterator cross_browser_context =
1449 if (cross_profile == cross_profile_map_.end()) 1446 cross_browser_context_map_.find(browser_context);
1447 if (cross_browser_context == cross_browser_context_map_.end())
1450 return false; 1448 return false;
1451 return cross_profile->second.first; 1449 return cross_browser_context->second.first;
1452 } 1450 }
1453 1451
1454 bool ExtensionWebRequestEventRouter::WasSignaled( 1452 bool ExtensionWebRequestEventRouter::WasSignaled(
1455 const net::URLRequest& request) const { 1453 const net::URLRequest& request) const {
1456 SignaledRequestMap::const_iterator flag = 1454 SignaledRequestMap::const_iterator flag =
1457 signaled_requests_.find(request.identifier()); 1455 signaled_requests_.find(request.identifier());
1458 return (flag != signaled_requests_.end()) && (flag->second != 0); 1456 return (flag != signaled_requests_.end()) && (flag->second != 0);
1459 } 1457 }
1460 1458
1461 void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( 1459 void ExtensionWebRequestEventRouter::GetMatchingListenersImpl(
1462 void* profile, 1460 void* browser_context,
1461 net::URLRequest* request,
1463 InfoMap* extension_info_map, 1462 InfoMap* extension_info_map,
1464 bool crosses_incognito, 1463 bool crosses_incognito,
1465 const std::string& event_name, 1464 const std::string& event_name,
1466 const GURL& url, 1465 const GURL& url,
1467 int tab_id,
1468 int window_id,
1469 int render_process_host_id, 1466 int render_process_host_id,
1470 int routing_id, 1467 int routing_id,
1471 ResourceType resource_type, 1468 ResourceType resource_type,
1472 bool is_async_request, 1469 bool is_async_request,
1473 bool is_request_from_extension, 1470 bool is_request_from_extension,
1474 int* extra_info_spec, 1471 int* extra_info_spec,
1475 std::vector<const ExtensionWebRequestEventRouter::EventListener*>* 1472 std::vector<const ExtensionWebRequestEventRouter::EventListener*>*
1476 matching_listeners) { 1473 matching_listeners) {
1477 std::string web_request_event_name(event_name); 1474 std::string web_request_event_name(event_name);
1478 extensions::WebViewRendererState::WebViewInfo web_view_info; 1475 extensions::WebViewRendererState::WebViewInfo web_view_info;
1479 bool is_web_view_guest = extensions::WebViewRendererState::GetInstance()-> 1476 bool is_web_view_guest = extensions::WebViewRendererState::GetInstance()->
1480 GetInfo(render_process_host_id, routing_id, &web_view_info); 1477 GetInfo(render_process_host_id, routing_id, &web_view_info);
1481 if (is_web_view_guest) { 1478 if (is_web_view_guest) {
1482 web_request_event_name.replace( 1479 web_request_event_name.replace(
1483 0, sizeof(kWebRequestEventPrefix) - 1, webview::kWebViewEventPrefix); 1480 0, sizeof(kWebRequestEventPrefix) - 1, webview::kWebViewEventPrefix);
1484 } 1481 }
1485 1482
1486 std::set<EventListener>& listeners = 1483 std::set<EventListener>& listeners =
1487 listeners_[profile][web_request_event_name]; 1484 listeners_[browser_context][web_request_event_name];
1488 for (std::set<EventListener>::iterator it = listeners.begin(); 1485 for (std::set<EventListener>::iterator it = listeners.begin();
1489 it != listeners.end(); ++it) { 1486 it != listeners.end(); ++it) {
1490 if (!it->ipc_sender.get()) { 1487 if (!it->ipc_sender.get()) {
1491 // The IPC sender has been deleted. This listener will be removed soon 1488 // The IPC sender has been deleted. This listener will be removed soon
1492 // via a call to RemoveEventListener. For now, just skip it. 1489 // via a call to RemoveEventListener. For now, just skip it.
1493 continue; 1490 continue;
1494 } 1491 }
1495 1492
1496 if (is_web_view_guest && 1493 if (is_web_view_guest &&
1497 (it->embedder_process_id != web_view_info.embedder_process_id || 1494 (it->embedder_process_id != web_view_info.embedder_process_id ||
1498 it->webview_instance_id != web_view_info.instance_id)) 1495 it->webview_instance_id != web_view_info.instance_id))
1499 continue; 1496 continue;
1500 1497
1501 if (!it->filter.urls.is_empty() && !it->filter.urls.MatchesURL(url)) 1498 if (!it->filter.urls.is_empty() && !it->filter.urls.MatchesURL(url))
1502 continue; 1499 continue;
1503 if (it->filter.tab_id != -1 && tab_id != it->filter.tab_id) 1500 if (it->filter.extra_request_params &&
1504 continue; 1501 it->filter.extra_request_params->OnGetMatchingListenersImplCheck(
1505 if (it->filter.window_id != -1 && window_id != it->filter.window_id) 1502 request))
1506 continue; 1503 continue;
1507 if (!it->filter.types.empty() && 1504 if (!it->filter.types.empty() &&
1508 std::find(it->filter.types.begin(), it->filter.types.end(), 1505 std::find(it->filter.types.begin(), it->filter.types.end(),
1509 resource_type) == it->filter.types.end()) 1506 resource_type) == it->filter.types.end())
1510 continue; 1507 continue;
1511 1508
1512 if (!is_web_view_guest && !WebRequestPermissions::CanExtensionAccessURL( 1509 if (!is_web_view_guest && !WebRequestPermissions::CanExtensionAccessURL(
1513 extension_info_map, it->extension_id, url, crosses_incognito, 1510 extension_info_map, it->extension_id, url, crosses_incognito,
1514 WebRequestPermissions::REQUIRE_HOST_PERMISSION)) 1511 WebRequestPermissions::REQUIRE_HOST_PERMISSION))
1515 continue; 1512 continue;
(...skipping 16 matching lines...) Expand all
1532 if (blocking_listener && synchronous_xhr_from_extension) 1529 if (blocking_listener && synchronous_xhr_from_extension)
1533 continue; 1530 continue;
1534 1531
1535 matching_listeners->push_back(&(*it)); 1532 matching_listeners->push_back(&(*it));
1536 *extra_info_spec |= it->extra_info_spec; 1533 *extra_info_spec |= it->extra_info_spec;
1537 } 1534 }
1538 } 1535 }
1539 1536
1540 std::vector<const ExtensionWebRequestEventRouter::EventListener*> 1537 std::vector<const ExtensionWebRequestEventRouter::EventListener*>
1541 ExtensionWebRequestEventRouter::GetMatchingListeners( 1538 ExtensionWebRequestEventRouter::GetMatchingListeners(
1542 void* profile, 1539 void* browser_context,
1543 InfoMap* extension_info_map, 1540 InfoMap* extension_info_map,
1544 const std::string& event_name, 1541 const std::string& event_name,
1545 net::URLRequest* request, 1542 net::URLRequest* request,
1546 int* extra_info_spec) { 1543 int* extra_info_spec) {
1547 // TODO(mpcomplete): handle profile == NULL (should collect all listeners). 1544 // TODO(mpcomplete): handle browser_context == NULL (should collect all
1545 // listeners).
1548 *extra_info_spec = 0; 1546 *extra_info_spec = 0;
1549 1547
1550 bool is_main_frame = false; 1548 bool is_main_frame = false;
1551 int frame_id = -1; 1549 int frame_id = -1;
1552 bool parent_is_main_frame = false; 1550 bool parent_is_main_frame = false;
1553 int parent_frame_id = -1; 1551 int parent_frame_id = -1;
1554 int tab_id = -1;
1555 int window_id = -1;
1556 int render_process_host_id = -1; 1552 int render_process_host_id = -1;
1557 int routing_id = -1; 1553 int routing_id = -1;
1558 ResourceType resource_type = content::RESOURCE_TYPE_LAST_TYPE; 1554 ResourceType resource_type = content::RESOURCE_TYPE_LAST_TYPE;
1559 const GURL& url = request->url(); 1555 const GURL& url = request->url();
1560 1556
1561 ExtractRequestInfoDetails(request, &is_main_frame, &frame_id, 1557 ExtractRequestInfoDetails(request, &is_main_frame, &frame_id,
1562 &parent_is_main_frame, &parent_frame_id, 1558 &parent_is_main_frame, &parent_frame_id,
1563 &tab_id, &window_id, &render_process_host_id, 1559 &render_process_host_id,
1564 &routing_id, &resource_type); 1560 &routing_id, &resource_type);
1565 1561
1566 std::vector<const ExtensionWebRequestEventRouter::EventListener*> 1562 std::vector<const ExtensionWebRequestEventRouter::EventListener*>
1567 matching_listeners; 1563 matching_listeners;
1568 1564
1569 bool is_request_from_extension = 1565 bool is_request_from_extension =
1570 IsRequestFromExtension(request, extension_info_map); 1566 IsRequestFromExtension(request, extension_info_map);
1571 1567
1572 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); 1568 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
1573 // We are conservative here and assume requests are asynchronous in case 1569 // We are conservative here and assume requests are asynchronous in case
1574 // we don't have an info object. We don't want to risk a deadlock. 1570 // we don't have an info object. We don't want to risk a deadlock.
1575 bool is_async_request = !info || info->IsAsync(); 1571 bool is_async_request = !info || info->IsAsync();
1576 1572
1577 GetMatchingListenersImpl( 1573 GetMatchingListenersImpl(
1578 profile, extension_info_map, false, event_name, url, 1574 browser_context, request, extension_info_map, false, event_name,
1579 tab_id, window_id, render_process_host_id, routing_id, resource_type, 1575 url, render_process_host_id, routing_id, resource_type,
1580 is_async_request, is_request_from_extension, extra_info_spec, 1576 is_async_request, is_request_from_extension, extra_info_spec,
1581 &matching_listeners); 1577 &matching_listeners);
1582 void* cross_profile = GetCrossProfile(profile); 1578 void* cross_browser_context = GetCrossBrowserContext(browser_context);
1583 if (cross_profile) { 1579 if (cross_browser_context) {
1584 GetMatchingListenersImpl( 1580 GetMatchingListenersImpl(
1585 cross_profile, extension_info_map, true, event_name, url, tab_id, 1581 cross_browser_context, request, extension_info_map, true, event_name,
1586 window_id, render_process_host_id, routing_id, resource_type, 1582 url, render_process_host_id, routing_id, resource_type,
1587 is_async_request, is_request_from_extension, extra_info_spec, 1583 is_async_request, is_request_from_extension, extra_info_spec,
1588 &matching_listeners); 1584 &matching_listeners);
1589 } 1585 }
1590 1586
1591 return matching_listeners; 1587 return matching_listeners;
1592 } 1588 }
1593 1589
1594 namespace { 1590 namespace {
1595 1591
1596 helpers::EventResponseDelta* CalculateDelta( 1592 helpers::EventResponseDelta* CalculateDelta(
(...skipping 28 matching lines...) Expand all
1625 return helpers::CalculateOnAuthRequiredDelta( 1621 return helpers::CalculateOnAuthRequiredDelta(
1626 response->extension_id, response->extension_install_time, 1622 response->extension_id, response->extension_install_time,
1627 response->cancel, &response->auth_credentials); 1623 response->cancel, &response->auth_credentials);
1628 default: 1624 default:
1629 NOTREACHED(); 1625 NOTREACHED();
1630 break; 1626 break;
1631 } 1627 }
1632 return NULL; 1628 return NULL;
1633 } 1629 }
1634 1630
1635 base::Value* SerializeResponseHeaders(const helpers::ResponseHeaders& headers) {
1636 scoped_ptr<base::ListValue> serialized_headers(new base::ListValue());
1637 for (helpers::ResponseHeaders::const_iterator i = headers.begin();
1638 i != headers.end(); ++i) {
1639 serialized_headers->Append(ToHeaderDictionary(i->first, i->second));
1640 }
1641 return serialized_headers.release();
1642 }
1643
1644 // Convert a RequestCookieModifications/ResponseCookieModifications object to a
1645 // base::ListValue which summarizes the changes made. This is templated since
1646 // the two types (request/response) are different but contain essentially the
1647 // same fields.
1648 template<typename CookieType>
1649 base::ListValue* SummarizeCookieModifications(
1650 const std::vector<linked_ptr<CookieType> >& modifications) {
1651 scoped_ptr<base::ListValue> cookie_modifications(new base::ListValue());
1652 for (typename std::vector<linked_ptr<CookieType> >::const_iterator i =
1653 modifications.begin();
1654 i != modifications.end(); ++i) {
1655 scoped_ptr<base::DictionaryValue> summary(new base::DictionaryValue());
1656 const CookieType& mod = *i->get();
1657 switch (mod.type) {
1658 case helpers::ADD:
1659 summary->SetString(activitylog::kCookieModificationTypeKey,
1660 activitylog::kCookieModificationAdd);
1661 break;
1662 case helpers::EDIT:
1663 summary->SetString(activitylog::kCookieModificationTypeKey,
1664 activitylog::kCookieModificationEdit);
1665 break;
1666 case helpers::REMOVE:
1667 summary->SetString(activitylog::kCookieModificationTypeKey,
1668 activitylog::kCookieModificationRemove);
1669 break;
1670 }
1671 if (mod.filter) {
1672 if (mod.filter->name)
1673 summary->SetString(activitylog::kCookieFilterNameKey,
1674 *mod.modification->name);
1675 if (mod.filter->domain)
1676 summary->SetString(activitylog::kCookieFilterDomainKey,
1677 *mod.modification->name);
1678 }
1679 if (mod.modification) {
1680 if (mod.modification->name)
1681 summary->SetString(activitylog::kCookieModDomainKey,
1682 *mod.modification->name);
1683 if (mod.modification->domain)
1684 summary->SetString(activitylog::kCookieModDomainKey,
1685 *mod.modification->name);
1686 }
1687 cookie_modifications->Append(summary.release());
1688 }
1689 return cookie_modifications.release();
1690 }
1691
1692 // Converts an EventResponseDelta object to a dictionary value suitable for the
1693 // activity log.
1694 scoped_ptr<base::DictionaryValue> SummarizeResponseDelta(
1695 const std::string& event_name,
1696 const helpers::EventResponseDelta& delta) {
1697 scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue());
1698 if (delta.cancel) {
1699 details->SetBoolean(activitylog::kCancelKey, true);
1700 }
1701 if (!delta.new_url.is_empty()) {
1702 details->SetString(activitylog::kNewUrlKey, delta.new_url.spec());
1703 }
1704
1705 scoped_ptr<base::ListValue> modified_headers(new base::ListValue());
1706 net::HttpRequestHeaders::Iterator iter(delta.modified_request_headers);
1707 while (iter.GetNext()) {
1708 modified_headers->Append(ToHeaderDictionary(iter.name(), iter.value()));
1709 }
1710 if (!modified_headers->empty()) {
1711 details->Set(activitylog::kModifiedRequestHeadersKey,
1712 modified_headers.release());
1713 }
1714
1715 scoped_ptr<base::ListValue> deleted_headers(new base::ListValue());
1716 deleted_headers->AppendStrings(delta.deleted_request_headers);
1717 if (!deleted_headers->empty()) {
1718 details->Set(activitylog::kDeletedRequestHeadersKey,
1719 deleted_headers.release());
1720 }
1721
1722 if (!delta.added_response_headers.empty()) {
1723 details->Set(activitylog::kAddedRequestHeadersKey,
1724 SerializeResponseHeaders(delta.added_response_headers));
1725 }
1726 if (!delta.deleted_response_headers.empty()) {
1727 details->Set(activitylog::kDeletedResponseHeadersKey,
1728 SerializeResponseHeaders(delta.deleted_response_headers));
1729 }
1730 if (delta.auth_credentials) {
1731 details->SetString(activitylog::kAuthCredentialsKey,
1732 base::UTF16ToUTF8(
1733 delta.auth_credentials->username()) + ":*");
1734 }
1735
1736 if (!delta.response_cookie_modifications.empty()) {
1737 details->Set(
1738 activitylog::kResponseCookieModificationsKey,
1739 SummarizeCookieModifications(delta.response_cookie_modifications));
1740 }
1741
1742 return details.Pass();
1743 }
1744
1745 void LogExtensionActivity(void* profile_id,
1746 bool is_incognito,
1747 const std::string& extension_id,
1748 const GURL& url,
1749 const std::string& api_call,
1750 scoped_ptr<base::DictionaryValue> details) {
1751 if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
1752 BrowserThread::PostTask(BrowserThread::UI,
1753 FROM_HERE,
1754 base::Bind(&LogExtensionActivity,
1755 profile_id,
1756 is_incognito,
1757 extension_id,
1758 url,
1759 api_call,
1760 base::Passed(&details)));
1761 } else {
1762 Profile* profile = static_cast<Profile*>(profile_id);
1763 if (!g_browser_process->profile_manager()->IsValidProfile(profile))
1764 return;
1765 scoped_refptr<extensions::Action> action =
1766 new extensions::Action(extension_id,
1767 base::Time::Now(),
1768 extensions::Action::ACTION_WEB_REQUEST,
1769 api_call);
1770 action->set_page_url(url);
1771 action->set_page_incognito(is_incognito);
1772 action->mutable_other()->Set(activity_log_constants::kActionWebRequest,
1773 details.release());
1774 extensions::ActivityLog::GetInstance(profile)->LogAction(action);
1775 }
1776 }
1777
1778 } // namespace 1631 } // namespace
1779 1632
1780 void ExtensionWebRequestEventRouter::DecrementBlockCount( 1633 void ExtensionWebRequestEventRouter::DecrementBlockCount(
1781 void* profile, 1634 void* browser_context,
1782 const std::string& extension_id, 1635 const std::string& extension_id,
1783 const std::string& event_name, 1636 const std::string& event_name,
1784 uint64 request_id, 1637 uint64 request_id,
1785 EventResponse* response) { 1638 EventResponse* response) {
1786 scoped_ptr<EventResponse> response_scoped(response); 1639 scoped_ptr<EventResponse> response_scoped(response);
1787 1640
1788 // It's possible that this request was deleted, or cancelled by a previous 1641 // It's possible that this request was deleted, or cancelled by a previous
1789 // event handler. If so, ignore this response. 1642 // event handler. If so, ignore this response.
1790 if (blocked_requests_.find(request_id) == blocked_requests_.end()) 1643 if (blocked_requests_.find(request_id) == blocked_requests_.end())
1791 return; 1644 return;
1792 1645
1793 BlockedRequest& blocked_request = blocked_requests_[request_id]; 1646 BlockedRequest& blocked_request = blocked_requests_[request_id];
1794 int num_handlers_blocking = --blocked_request.num_handlers_blocking; 1647 int num_handlers_blocking = --blocked_request.num_handlers_blocking;
1795 CHECK_GE(num_handlers_blocking, 0); 1648 CHECK_GE(num_handlers_blocking, 0);
1796 1649
1797 if (response) { 1650 if (response) {
1798 helpers::EventResponseDelta* delta = 1651 helpers::EventResponseDelta* delta =
1799 CalculateDelta(&blocked_request, response); 1652 CalculateDelta(&blocked_request, response);
1800 1653
1801 LogExtensionActivity(profile, 1654 if (web_request_event_router_delegate_) {
1802 blocked_request.is_incognito, 1655 web_request_event_router_delegate_->LogExtensionActivity(
1803 extension_id, 1656 browser_context,
1804 blocked_request.request->url(), 1657 blocked_request.is_incognito,
1805 event_name, 1658 extension_id,
1806 SummarizeResponseDelta(event_name, *delta)); 1659 blocked_request.request->url(),
1660 event_name,
1661 *delta);
1662 }
1807 1663
1808 blocked_request.response_deltas.push_back( 1664 blocked_request.response_deltas.push_back(
1809 linked_ptr<helpers::EventResponseDelta>(delta)); 1665 linked_ptr<helpers::EventResponseDelta>(delta));
1810 } 1666 }
1811 1667
1812 base::TimeDelta block_time = 1668 base::TimeDelta block_time =
1813 base::Time::Now() - blocked_request.blocking_time; 1669 base::Time::Now() - blocked_request.blocking_time;
1814 if (!extension_id.empty()) { 1670 if (!extension_id.empty()) {
1815 request_time_tracker_->IncrementExtensionBlockTime( 1671 request_time_tracker_->IncrementExtensionBlockTime(
1816 extension_id, request_id, block_time); 1672 extension_id, request_id, block_time);
1817 } else { 1673 } else {
1818 // |extension_id| is empty for requests blocked on startup waiting for the 1674 // |extension_id| is empty for requests blocked on startup waiting for the
1819 // declarative rules to be read from disk. 1675 // declarative rules to be read from disk.
1820 UMA_HISTOGRAM_TIMES("Extensions.NetworkDelayStartup", block_time); 1676 UMA_HISTOGRAM_TIMES("Extensions.NetworkDelayStartup", block_time);
1821 } 1677 }
1822 1678
1823 if (num_handlers_blocking == 0) { 1679 if (num_handlers_blocking == 0) {
1824 blocked_request.request->LogUnblocked(); 1680 blocked_request.request->LogUnblocked();
1825 ExecuteDeltas(profile, request_id, true); 1681 ExecuteDeltas(browser_context, request_id, true);
1826 } else { 1682 } else {
1827 // Update the URLRequest to make sure it's tagged with an extension that's 1683 // Update the URLRequest to make sure it's tagged with an extension that's
1828 // still blocking it. This may end up being the same extension as before. 1684 // still blocking it. This may end up being the same extension as before.
1829 std::set<EventListener>& listeners = listeners_[profile][event_name]; 1685 std::set<EventListener>& listeners =
1686 listeners_[browser_context][event_name];
1830 1687
1831 for (std::set<EventListener>::iterator it = listeners.begin(); 1688 for (std::set<EventListener>::iterator it = listeners.begin();
1832 it != listeners.end(); ++it) { 1689 it != listeners.end(); ++it) {
1833 if (it->blocked_requests.count(request_id) == 0) 1690 if (it->blocked_requests.count(request_id) == 0)
1834 continue; 1691 continue;
1835 std::string delegate_info = 1692 std::string delegate_info =
1836 l10n_util::GetStringFUTF8(IDS_LOAD_STATE_PARAMETER_EXTENSION, 1693 l10n_util::GetStringFUTF8(IDS_LOAD_STATE_PARAMETER_EXTENSION,
1837 base::UTF8ToUTF16(it->extension_name)); 1694 base::UTF8ToUTF16(it->extension_name));
1838 blocked_request.request->LogAndReportBlockedBy(delegate_info.c_str()); 1695 blocked_request.request->LogAndReportBlockedBy(delegate_info.c_str());
1839 break; 1696 break;
1840 } 1697 }
1841 } 1698 }
1842 } 1699 }
1843 1700
1844 void ExtensionWebRequestEventRouter::SendMessages( 1701 void ExtensionWebRequestEventRouter::SendMessages(
1845 void* profile, 1702 void* browser_context,
1846 const BlockedRequest& blocked_request) { 1703 const BlockedRequest& blocked_request) {
1847 const helpers::EventResponseDeltas& deltas = blocked_request.response_deltas; 1704 const helpers::EventResponseDeltas& deltas = blocked_request.response_deltas;
1848 for (helpers::EventResponseDeltas::const_iterator delta = deltas.begin(); 1705 for (helpers::EventResponseDeltas::const_iterator delta = deltas.begin();
1849 delta != deltas.end(); ++delta) { 1706 delta != deltas.end(); ++delta) {
1850 const std::set<std::string>& messages = (*delta)->messages_to_extension; 1707 const std::set<std::string>& messages = (*delta)->messages_to_extension;
1851 for (std::set<std::string>::const_iterator message = messages.begin(); 1708 for (std::set<std::string>::const_iterator message = messages.begin();
1852 message != messages.end(); ++message) { 1709 message != messages.end(); ++message) {
1853 scoped_ptr<base::DictionaryValue> argument(new base::DictionaryValue); 1710 scoped_ptr<base::DictionaryValue> argument(new base::DictionaryValue);
1854 ExtractRequestInfo(blocked_request.request, argument.get()); 1711 ExtractRequestInfo(blocked_request.request, argument.get());
1855 extensions::WebViewRendererState::WebViewInfo web_view_info; 1712 extensions::WebViewRendererState::WebViewInfo web_view_info;
1856 bool is_web_view_guest = GetWebViewInfo(blocked_request.request, 1713 bool is_web_view_guest = GetWebViewInfo(blocked_request.request,
1857 &web_view_info); 1714 &web_view_info);
1858 argument->SetString(keys::kMessageKey, *message); 1715 argument->SetString(keys::kMessageKey, *message);
1859 argument->SetString(keys::kStageKey, 1716 argument->SetString(keys::kStageKey,
1860 GetRequestStageAsString(blocked_request.event)); 1717 GetRequestStageAsString(blocked_request.event));
1861 1718
1862 BrowserThread::PostTask( 1719 BrowserThread::PostTask(
1863 BrowserThread::UI, 1720 BrowserThread::UI,
1864 FROM_HERE, 1721 FROM_HERE,
1865 base::Bind(&SendOnMessageEventOnUI, 1722 base::Bind(&SendOnMessageEventOnUI,
1866 profile, 1723 browser_context,
1867 (*delta)->extension_id, 1724 (*delta)->extension_id,
1868 is_web_view_guest, 1725 is_web_view_guest,
1869 web_view_info, 1726 web_view_info,
1870 base::Passed(&argument))); 1727 base::Passed(&argument)));
1871 } 1728 }
1872 } 1729 }
1873 } 1730 }
1874 1731
1875 int ExtensionWebRequestEventRouter::ExecuteDeltas( 1732 int ExtensionWebRequestEventRouter::ExecuteDeltas(
1876 void* profile, 1733 void* browser_context,
1877 uint64 request_id, 1734 uint64 request_id,
1878 bool call_callback) { 1735 bool call_callback) {
1879 BlockedRequest& blocked_request = blocked_requests_[request_id]; 1736 BlockedRequest& blocked_request = blocked_requests_[request_id];
1880 CHECK(blocked_request.num_handlers_blocking == 0); 1737 CHECK(blocked_request.num_handlers_blocking == 0);
1881 helpers::EventResponseDeltas& deltas = blocked_request.response_deltas; 1738 helpers::EventResponseDeltas& deltas = blocked_request.response_deltas;
1882 base::TimeDelta block_time = 1739 base::TimeDelta block_time =
1883 base::Time::Now() - blocked_request.blocking_time; 1740 base::Time::Now() - blocked_request.blocking_time;
1884 request_time_tracker_->IncrementTotalBlockTime(request_id, block_time); 1741 request_time_tracker_->IncrementTotalBlockTime(request_id, block_time);
1885 1742
1886 bool credentials_set = false; 1743 bool credentials_set = false;
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
1922 CHECK(!blocked_request.auth_callback.is_null()); 1779 CHECK(!blocked_request.auth_callback.is_null());
1923 credentials_set = helpers::MergeOnAuthRequiredResponses( 1780 credentials_set = helpers::MergeOnAuthRequiredResponses(
1924 blocked_request.response_deltas, 1781 blocked_request.response_deltas,
1925 blocked_request.auth_credentials, 1782 blocked_request.auth_credentials,
1926 &warnings, 1783 &warnings,
1927 blocked_request.net_log); 1784 blocked_request.net_log);
1928 } else { 1785 } else {
1929 NOTREACHED(); 1786 NOTREACHED();
1930 } 1787 }
1931 1788
1932 SendMessages(profile, blocked_request); 1789 SendMessages(browser_context, blocked_request);
1933 1790
1934 if (!warnings.empty()) { 1791 if (!warnings.empty()) {
1935 BrowserThread::PostTask( 1792 BrowserThread::PostTask(
1936 BrowserThread::UI, 1793 BrowserThread::UI,
1937 FROM_HERE, 1794 FROM_HERE,
1938 base::Bind(&WarningService::NotifyWarningsOnUI, profile, warnings)); 1795 base::Bind(&WarningService::NotifyWarningsOnUI,
1796 browser_context, warnings));
1939 } 1797 }
1940 1798
1941 if (canceled) { 1799 if (canceled) {
1942 request_time_tracker_->SetRequestCanceled(request_id); 1800 request_time_tracker_->SetRequestCanceled(request_id);
1943 } else if (blocked_request.new_url && 1801 } else if (blocked_request.new_url &&
1944 !blocked_request.new_url->is_empty()) { 1802 !blocked_request.new_url->is_empty()) {
1945 request_time_tracker_->SetRequestRedirected(request_id); 1803 request_time_tracker_->SetRequestRedirected(request_id);
1946 } 1804 }
1947 1805
1948 // This triggers onErrorOccurred if canceled is true. 1806 // This triggers onErrorOccurred if canceled is true.
(...skipping 18 matching lines...) Expand all
1967 blocked_requests_.erase(request_id); 1825 blocked_requests_.erase(request_id);
1968 if (call_callback) 1826 if (call_callback)
1969 callback.Run(response); 1827 callback.Run(response);
1970 } else { 1828 } else {
1971 blocked_requests_.erase(request_id); 1829 blocked_requests_.erase(request_id);
1972 } 1830 }
1973 return rv; 1831 return rv;
1974 } 1832 }
1975 1833
1976 bool ExtensionWebRequestEventRouter::ProcessDeclarativeRules( 1834 bool ExtensionWebRequestEventRouter::ProcessDeclarativeRules(
1977 void* profile, 1835 void* browser_context,
1978 InfoMap* extension_info_map, 1836 InfoMap* extension_info_map,
1979 const std::string& event_name, 1837 const std::string& event_name,
1980 net::URLRequest* request, 1838 net::URLRequest* request,
1981 extensions::RequestStage request_stage, 1839 extensions::RequestStage request_stage,
1982 const net::HttpResponseHeaders* original_response_headers) { 1840 const net::HttpResponseHeaders* original_response_headers) {
1983 extensions::WebViewRendererState::WebViewInfo web_view_info; 1841 extensions::WebViewRendererState::WebViewInfo web_view_info;
1984 bool is_web_view_guest = GetWebViewInfo(request, &web_view_info); 1842 bool is_web_view_guest = GetWebViewInfo(request, &web_view_info);
1985 1843
1986 RulesRegistryService::WebViewKey webview_key( 1844 RulesRegistryService::WebViewKey webview_key(
1987 is_web_view_guest ? web_view_info.embedder_process_id : 0, 1845 is_web_view_guest ? web_view_info.embedder_process_id : 0,
1988 is_web_view_guest ? web_view_info.instance_id : 0); 1846 is_web_view_guest ? web_view_info.instance_id : 0);
1989 RulesRegistryKey rules_key(profile, webview_key); 1847 RulesRegistryKey rules_key(browser_context, webview_key);
1990 // If this check fails, check that the active stages are up-to-date in 1848 // If this check fails, check that the active stages are up-to-date in
1991 // extensions/browser/api/declarative_webrequest/request_stage.h . 1849 // extensions/browser/api/declarative_webrequest/request_stage.h .
1992 DCHECK(request_stage & extensions::kActiveStages); 1850 DCHECK(request_stage & extensions::kActiveStages);
1993 1851
1994 // Rules of the current |profile| may apply but we need to check also whether 1852 // Rules of the current |browser_context| may apply but we need to check also
1995 // there are applicable rules from extensions whose background page 1853 // whether there are applicable rules from extensions whose background page
1996 // spans from regular to incognito mode. 1854 // spans from regular to incognito mode.
1997 1855
1998 // First parameter identifies the registry, the second indicates whether the 1856 // First parameter identifies the registry, the second indicates whether the
1999 // registry belongs to the cross profile. 1857 // registry belongs to the cross browser_context.
2000 typedef std::pair<extensions::WebRequestRulesRegistry*, bool> 1858 typedef std::pair<extensions::WebRequestRulesRegistry*, bool>
2001 RelevantRegistry; 1859 RelevantRegistry;
2002 typedef std::vector<RelevantRegistry> RelevantRegistries; 1860 typedef std::vector<RelevantRegistry> RelevantRegistries;
2003 RelevantRegistries relevant_registries; 1861 RelevantRegistries relevant_registries;
2004 1862
2005 if (rules_registries_.find(rules_key) != rules_registries_.end()) { 1863 if (rules_registries_.find(rules_key) != rules_registries_.end()) {
2006 relevant_registries.push_back( 1864 relevant_registries.push_back(
2007 std::make_pair(rules_registries_[rules_key].get(), false)); 1865 std::make_pair(rules_registries_[rules_key].get(), false));
2008 } 1866 }
2009 1867
2010 void* cross_profile = GetCrossProfile(profile); 1868 void* cross_browser_context = GetCrossBrowserContext(browser_context);
2011 RulesRegistryKey cross_profile_rules_key(cross_profile, webview_key); 1869 RulesRegistryKey cross_browser_context_rules_key(
2012 if (cross_profile && 1870 cross_browser_context, webview_key);
2013 rules_registries_.find(cross_profile_rules_key) != 1871 if (cross_browser_context &&
1872 rules_registries_.find(cross_browser_context_rules_key) !=
2014 rules_registries_.end()) { 1873 rules_registries_.end()) {
2015 relevant_registries.push_back( 1874 relevant_registries.push_back(
2016 std::make_pair(rules_registries_[cross_profile_rules_key].get(), true)); 1875 std::make_pair(
1876 rules_registries_[cross_browser_context_rules_key].get(), true));
2017 } 1877 }
2018 1878
2019 // The following block is experimentally enabled and its impact on load time 1879 // The following block is experimentally enabled and its impact on load time
2020 // logged with UMA Extensions.NetworkDelayRegistryLoad. crbug.com/175961 1880 // logged with UMA Extensions.NetworkDelayRegistryLoad. crbug.com/175961
2021 for (RelevantRegistries::iterator i = relevant_registries.begin(); 1881 for (RelevantRegistries::iterator i = relevant_registries.begin();
2022 i != relevant_registries.end(); ++i) { 1882 i != relevant_registries.end(); ++i) {
2023 extensions::WebRequestRulesRegistry* rules_registry = i->first; 1883 extensions::WebRequestRulesRegistry* rules_registry = i->first;
2024 if (!rules_registry->ready().is_signaled()) { 1884 if (!rules_registry->ready().is_signaled()) {
2025 // The rules registry is still loading. Block this request until it 1885 // The rules registry is still loading. Block this request until it
2026 // finishes. 1886 // finishes.
2027 rules_registry->ready().Post( 1887 rules_registry->ready().Post(
2028 FROM_HERE, 1888 FROM_HERE,
2029 base::Bind(&ExtensionWebRequestEventRouter::OnRulesRegistryReady, 1889 base::Bind(&ExtensionWebRequestEventRouter::OnRulesRegistryReady,
2030 AsWeakPtr(), 1890 AsWeakPtr(),
2031 profile, 1891 browser_context,
2032 event_name, 1892 event_name,
2033 request->identifier(), 1893 request->identifier(),
2034 request_stage)); 1894 request_stage));
2035 blocked_requests_[request->identifier()].num_handlers_blocking++; 1895 blocked_requests_[request->identifier()].num_handlers_blocking++;
2036 blocked_requests_[request->identifier()].request = request; 1896 blocked_requests_[request->identifier()].request = request;
2037 blocked_requests_[request->identifier()].is_incognito |= 1897 blocked_requests_[request->identifier()].is_incognito |=
2038 IsIncognitoProfile(profile); 1898 IsIncognitoBrowserContext(browser_context);
2039 blocked_requests_[request->identifier()].blocking_time = 1899 blocked_requests_[request->identifier()].blocking_time =
2040 base::Time::Now(); 1900 base::Time::Now();
2041 blocked_requests_[request->identifier()].original_response_headers = 1901 blocked_requests_[request->identifier()].original_response_headers =
2042 original_response_headers; 1902 original_response_headers;
2043 blocked_requests_[request->identifier()].extension_info_map = 1903 blocked_requests_[request->identifier()].extension_info_map =
2044 extension_info_map; 1904 extension_info_map;
2045 return true; 1905 return true;
2046 } 1906 }
2047 } 1907 }
2048 1908
(...skipping 20 matching lines...) Expand all
2069 } 1929 }
2070 1930
2071 base::TimeDelta elapsed_time = start - base::Time::Now(); 1931 base::TimeDelta elapsed_time = start - base::Time::Now();
2072 UMA_HISTOGRAM_TIMES("Extensions.DeclarativeWebRequestNetworkDelay", 1932 UMA_HISTOGRAM_TIMES("Extensions.DeclarativeWebRequestNetworkDelay",
2073 elapsed_time); 1933 elapsed_time);
2074 1934
2075 return deltas_created; 1935 return deltas_created;
2076 } 1936 }
2077 1937
2078 void ExtensionWebRequestEventRouter::OnRulesRegistryReady( 1938 void ExtensionWebRequestEventRouter::OnRulesRegistryReady(
2079 void* profile, 1939 void* browser_context,
2080 const std::string& event_name, 1940 const std::string& event_name,
2081 uint64 request_id, 1941 uint64 request_id,
2082 extensions::RequestStage request_stage) { 1942 extensions::RequestStage request_stage) {
2083 // It's possible that this request was deleted, or cancelled by a previous 1943 // It's possible that this request was deleted, or cancelled by a previous
2084 // event handler. If so, ignore this response. 1944 // event handler. If so, ignore this response.
2085 if (blocked_requests_.find(request_id) == blocked_requests_.end()) 1945 if (blocked_requests_.find(request_id) == blocked_requests_.end())
2086 return; 1946 return;
2087 1947
2088 BlockedRequest& blocked_request = blocked_requests_[request_id]; 1948 BlockedRequest& blocked_request = blocked_requests_[request_id];
2089 base::TimeDelta block_time = 1949 base::TimeDelta block_time =
2090 base::Time::Now() - blocked_request.blocking_time; 1950 base::Time::Now() - blocked_request.blocking_time;
2091 UMA_HISTOGRAM_TIMES("Extensions.NetworkDelayRegistryLoad", block_time); 1951 UMA_HISTOGRAM_TIMES("Extensions.NetworkDelayRegistryLoad", block_time);
2092 1952
2093 ProcessDeclarativeRules(profile, 1953 ProcessDeclarativeRules(browser_context,
2094 blocked_request.extension_info_map, 1954 blocked_request.extension_info_map,
2095 event_name, 1955 event_name,
2096 blocked_request.request, 1956 blocked_request.request,
2097 request_stage, 1957 request_stage,
2098 blocked_request.original_response_headers.get()); 1958 blocked_request.original_response_headers.get());
2099 // Reset to NULL so that nobody relies on this being set. 1959 // Reset to NULL so that nobody relies on this being set.
2100 blocked_request.extension_info_map = NULL; 1960 blocked_request.extension_info_map = NULL;
2101 DecrementBlockCount(profile, std::string(), event_name, request_id, NULL); 1961 DecrementBlockCount(
1962 browser_context, std::string(), event_name, request_id, NULL);
2102 } 1963 }
2103 1964
2104 bool ExtensionWebRequestEventRouter::GetAndSetSignaled(uint64 request_id, 1965 bool ExtensionWebRequestEventRouter::GetAndSetSignaled(uint64 request_id,
2105 EventTypes event_type) { 1966 EventTypes event_type) {
2106 SignaledRequestMap::iterator iter = signaled_requests_.find(request_id); 1967 SignaledRequestMap::iterator iter = signaled_requests_.find(request_id);
2107 if (iter == signaled_requests_.end()) { 1968 if (iter == signaled_requests_.end()) {
2108 signaled_requests_[request_id] = event_type; 1969 signaled_requests_[request_id] = event_type;
2109 return false; 1970 return false;
2110 } 1971 }
2111 bool was_signaled_before = (iter->second & event_type) != 0; 1972 bool was_signaled_before = (iter->second & event_type) != 0;
(...skipping 356 matching lines...) Expand 10 before | Expand all | Expand 10 after
2468 // Continue gracefully. 2329 // Continue gracefully.
2469 RunSync(); 2330 RunSync();
2470 } 2331 }
2471 2332
2472 bool WebRequestHandlerBehaviorChangedFunction::RunSync() { 2333 bool WebRequestHandlerBehaviorChangedFunction::RunSync() {
2473 helpers::ClearCacheOnNavigation(); 2334 helpers::ClearCacheOnNavigation();
2474 return true; 2335 return true;
2475 } 2336 }
2476 2337
2477 void SendExtensionWebRequestStatusToHost(content::RenderProcessHost* host) { 2338 void SendExtensionWebRequestStatusToHost(content::RenderProcessHost* host) {
2478 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext()); 2339 content::BrowserContext* browser_context = host->GetBrowserContext();
2479 if (!profile) 2340 if (!browser_context)
2480 return; 2341 return;
2481 2342
2482 bool webrequest_used = false; 2343 bool webrequest_used = false;
2483 const extensions::ExtensionSet& extensions = 2344 const extensions::ExtensionSet& extensions =
2484 extensions::ExtensionRegistry::Get(profile)->enabled_extensions(); 2345 extensions::ExtensionRegistry::Get(browser_context)->enabled_extensions();
2485 extensions::RuntimeData* runtime_data = 2346 extensions::RuntimeData* runtime_data =
2486 extensions::ExtensionSystem::Get(profile)->runtime_data(); 2347 extensions::ExtensionSystem::Get(browser_context)->runtime_data();
2487 for (extensions::ExtensionSet::const_iterator it = extensions.begin(); 2348 for (extensions::ExtensionSet::const_iterator it = extensions.begin();
2488 !webrequest_used && it != extensions.end(); 2349 !webrequest_used && it != extensions.end();
2489 ++it) { 2350 ++it) {
2490 webrequest_used |= runtime_data->HasUsedWebRequest(it->get()); 2351 webrequest_used |= runtime_data->HasUsedWebRequest(it->get());
2491 } 2352 }
2492 2353
2493 host->Send(new ExtensionMsg_UsingWebRequestAPI(webrequest_used)); 2354 host->Send(new ExtensionMsg_UsingWebRequestAPI(webrequest_used));
2494 } 2355 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698