diff options
author | thestig <thestig@chromium.org> | 2015-08-20 16:15:06 -0700 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2015-08-20 23:16:19 +0000 |
commit | 7041b48348a4175ec200f6d1e9750b2e1989080f (patch) | |
tree | 95fac0379b112dfd2048e6840dda05ae362af630 /extensions | |
parent | f0174383065041b7a6295b030d6a0e2300eea829 (diff) | |
download | chromium_src-7041b48348a4175ec200f6d1e9750b2e1989080f.zip chromium_src-7041b48348a4175ec200f6d1e9750b2e1989080f.tar.gz chromium_src-7041b48348a4175ec200f6d1e9750b2e1989080f.tar.bz2 |
Cleanup web_request_api.cc:
- Put common code in functions.
- Use range-based for loops.
- Style nits.
Review URL: https://codereview.chromium.org/1288873008
Cr-Commit-Position: refs/heads/master@{#344609}
Diffstat (limited to 'extensions')
4 files changed, 346 insertions, 367 deletions
diff --git a/extensions/browser/api/web_request/web_request_api.cc b/extensions/browser/api/web_request/web_request_api.cc index 279276b..0aaa4fa 100644 --- a/extensions/browser/api/web_request/web_request_api.cc +++ b/extensions/browser/api/web_request/web_request_api.cc @@ -138,7 +138,7 @@ bool IsWebRequestEvent(const std::string& event_name) { web_request_event_name.replace( 0, strlen(webview::kWebViewEventPrefix), kWebRequestEventPrefix); } - auto web_request_events_end = + const auto web_request_events_end = kWebRequestEvents + arraysize(kWebRequestEvents); return std::find(kWebRequestEvents, web_request_events_end, web_request_event_name) != web_request_events_end; @@ -162,7 +162,7 @@ bool IsRequestFromExtension(const net::URLRequest* request, return extension_info_map->process_map().Contains(info->GetChildID()); } -void ExtractRequestRoutingInfo(net::URLRequest* request, +void ExtractRequestRoutingInfo(const net::URLRequest* request, int* render_process_host_id, int* routing_id) { if (!request->GetUserData(NULL)) @@ -176,7 +176,7 @@ void ExtractRequestRoutingInfo(net::URLRequest* request, // a <webview> guest process or not. If it is from a <webview> guest process, // then |web_view_info| is returned with information about the instance ID // that uniquely identifies the <webview> and its embedder. -bool GetWebViewInfo(net::URLRequest* request, +bool GetWebViewInfo(const net::URLRequest* request, WebViewRendererState::WebViewInfo* web_view_info) { int render_process_host_id = -1; int routing_id = -1; @@ -185,7 +185,7 @@ bool GetWebViewInfo(net::URLRequest* request, render_process_host_id, routing_id, web_view_info); } -void ExtractRequestInfoDetails(net::URLRequest* request, +void ExtractRequestInfoDetails(const net::URLRequest* request, bool* is_main_frame, int* frame_id, bool* parent_is_main_frame, @@ -216,8 +216,9 @@ void ExtractRequestInfoBody(const net::URLRequest* request, base::DictionaryValue* out) { const net::UploadDataStream* upload_data = request->get_upload(); if (!upload_data || - (request->method() != "POST" && request->method() != "PUT")) + (request->method() != "POST" && request->method() != "PUT")) { return; // Need to exit without "out->Set(keys::kRequestBodyKey, ...);" . + } base::DictionaryValue* request_body = new base::DictionaryValue(); out->Set(keys::kRequestBodyKey, request_body); @@ -239,13 +240,13 @@ void ExtractRequestInfoBody(const net::URLRequest* request, upload_data->GetElementReaders(); bool some_succeeded = false; if (readers) { - for (size_t i = 0; !some_succeeded && i < arraysize(presenters); ++i) { - ScopedVector<net::UploadElementReader>::const_iterator reader; - for (reader = readers->begin(); reader != readers->end(); ++reader) - presenters[i]->FeedNext(**reader); + for (size_t i = 0; i < arraysize(presenters); ++i) { + for (const auto& reader : *readers) + presenters[i]->FeedNext(*reader); if (presenters[i]->Succeeded()) { request_body->Set(kKeys[i], presenters[i]->Result().release()); some_succeeded = true; + break; } } } @@ -263,8 +264,9 @@ bool FromHeaderDictionary(const base::DictionaryValue* header_value, // We require either a "value" or a "binaryValue" entry. if (!(header_value->HasKey(keys::kHeaderValueKey) ^ - header_value->HasKey(keys::kHeaderBinaryValueKey))) + header_value->HasKey(keys::kHeaderBinaryValueKey))) { return false; + } if (header_value->HasKey(keys::kHeaderValueKey)) { if (!header_value->GetString(keys::kHeaderValueKey, value)) { @@ -312,6 +314,13 @@ base::StringValue* GetStatusLine(net::HttpResponseHeaders* headers) { headers ? headers->GetStatusLine() : std::string()); } +// Returns the response code from the response headers, or 200 by default. +// |headers| may be NULL, e.g. UrlRequestFileJobs do not send headers, so +// simulate their behavior. +int GetResponseCodeWithDefault(net::HttpResponseHeaders* headers) { + return headers ? headers->response_code() : 200; +} + // Sends an event to subscribers of chrome.declarativeWebRequest.onMessage or // to subscribers of webview.onMessage if the action is being operated upon // a <webview> guest renderer. @@ -377,7 +386,7 @@ events::HistogramValue GetEventHistogramValue(const std::string& event_name) { // view) events that map to webRequest events. Check webRequest first. static struct ValueAndName { events::HistogramValue histogram_value; - const char* event_name; + const char* const event_name; } values_and_names[] = { {events::WEB_REQUEST_ON_BEFORE_REDIRECT, keys::kOnBeforeRedirectEvent}, {events::WEB_REQUEST_ON_BEFORE_REQUEST, @@ -408,7 +417,15 @@ events::HistogramValue GetEventHistogramValue(const std::string& event_name) { // either the mapping here, or in guest_view_events. NOTREACHED() << "Event " << event_name << " must have a histogram value"; return events::UNKNOWN; -}; +} + +// We hide events from the system context as well as sensitive requests. +bool ShouldHideEvent(void* browser_context, + const InfoMap* extension_info_map, + const net::URLRequest* request) { + return (!browser_context || + WebRequestPermissions::HideRequest(extension_info_map, request)); +} } // namespace @@ -474,7 +491,7 @@ struct ExtensionWebRequestEventRouter::EventListener { int embedder_process_id; int web_view_instance_id; base::WeakPtr<IPC::Sender> ipc_sender; - mutable std::set<uint64> blocked_requests; + mutable std::set<uint64_t> blocked_requests; // Comparator to work with std::set. bool operator<(const EventListener& that) const { @@ -564,7 +581,7 @@ struct ExtensionWebRequestEventRouter::BlockedRequest { // Provider of meta data about extensions, only used and non-NULL for events // that are delayed until the rules registry is ready. - InfoMap* extension_info_map; + const InfoMap* extension_info_map; BlockedRequest() : request(NULL), @@ -611,8 +628,9 @@ bool ExtensionWebRequestEventRouter::RequestFilter::InitFromValue( std::string type_str; ResourceType type; if (!types_value->GetString(i, &type_str) || - !helpers::ParseResourceType(type_str, &type)) + !helpers::ParseResourceType(type_str, &type)) { return false; + } types.push_back(type); } } else if (it.key() == "tabId") { @@ -705,7 +723,8 @@ void ExtensionWebRequestEventRouter::RegisterRulesRegistry( } void ExtensionWebRequestEventRouter::ExtractRequestInfo( - net::URLRequest* request, base::DictionaryValue* out) { + const net::URLRequest* request, + base::DictionaryValue* out) { bool is_main_frame = false; int frame_id = -1; bool parent_is_main_frame = false; @@ -739,13 +758,11 @@ void ExtensionWebRequestEventRouter::ExtractRequestInfo( int ExtensionWebRequestEventRouter::OnBeforeRequest( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, const net::CompletionCallback& callback, GURL* new_url) { - // We hide events from the system context as well as sensitive requests. - if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + if (ShouldHideEvent(browser_context, extension_info_map, request)) return net::OK; if (IsPageLoad(request)) @@ -756,7 +773,7 @@ int ExtensionWebRequestEventRouter::OnBeforeRequest( request->url(), browser_context); - // Whether to initialized blocked_requests_. + // Whether to initialized |blocked_requests_|. bool initialize_blocked_requests = false; initialize_blocked_requests |= @@ -765,10 +782,9 @@ int ExtensionWebRequestEventRouter::OnBeforeRequest( ON_BEFORE_REQUEST, NULL); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - web_request::OnBeforeRequest::kEventName, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, + web_request::OnBeforeRequest::kEventName, request, &extra_info_spec); if (!listeners.empty() && !GetAndSetSignaled(request->identifier(), kOnBeforeRequest)) { base::ListValue args; @@ -785,33 +801,30 @@ int ExtensionWebRequestEventRouter::OnBeforeRequest( if (!initialize_blocked_requests) return net::OK; // Nobody saw a reason for modifying the request. - blocked_requests_[request->identifier()].event = kOnBeforeRequest; - blocked_requests_[request->identifier()].is_incognito |= - IsIncognitoBrowserContext(browser_context); - blocked_requests_[request->identifier()].request = request; - blocked_requests_[request->identifier()].callback = callback; - blocked_requests_[request->identifier()].new_url = new_url; - blocked_requests_[request->identifier()].net_log = &request->net_log(); + BlockedRequest& blocked_request = blocked_requests_[request->identifier()]; + blocked_request.event = kOnBeforeRequest; + blocked_request.is_incognito |= IsIncognitoBrowserContext(browser_context); + blocked_request.request = request; + blocked_request.callback = callback; + blocked_request.new_url = new_url; + blocked_request.net_log = &request->net_log(); - if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) { + if (blocked_request.num_handlers_blocking == 0) { // If there are no blocking handlers, only the declarative rules tried // to modify the request and we can respond synchronously. return ExecuteDeltas(browser_context, request->identifier(), false /* call_callback*/); - } else { - return net::ERR_IO_PENDING; } + return net::ERR_IO_PENDING; } int ExtensionWebRequestEventRouter::OnBeforeSendHeaders( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, const net::CompletionCallback& callback, net::HttpRequestHeaders* headers) { - // We hide events from the system context as well as sensitive requests. - if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + if (ShouldHideEvent(browser_context, extension_info_map, request)) return net::OK; bool initialize_blocked_requests = false; @@ -821,10 +834,9 @@ int ExtensionWebRequestEventRouter::OnBeforeSendHeaders( request, ON_BEFORE_SEND_HEADERS, NULL); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - keys::kOnBeforeSendHeadersEvent, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, keys::kOnBeforeSendHeadersEvent, + request, &extra_info_spec); if (!listeners.empty() && !GetAndSetSignaled(request->identifier(), kOnBeforeSendHeaders)) { base::ListValue args; @@ -841,32 +853,29 @@ int ExtensionWebRequestEventRouter::OnBeforeSendHeaders( if (!initialize_blocked_requests) return net::OK; // Nobody saw a reason for modifying the request. - blocked_requests_[request->identifier()].event = kOnBeforeSendHeaders; - blocked_requests_[request->identifier()].is_incognito |= - IsIncognitoBrowserContext(browser_context); - blocked_requests_[request->identifier()].request = request; - blocked_requests_[request->identifier()].callback = callback; - blocked_requests_[request->identifier()].request_headers = headers; - blocked_requests_[request->identifier()].net_log = &request->net_log(); + BlockedRequest& blocked_request = blocked_requests_[request->identifier()]; + blocked_request.event = kOnBeforeSendHeaders; + blocked_request.is_incognito |= IsIncognitoBrowserContext(browser_context); + blocked_request.request = request; + blocked_request.callback = callback; + blocked_request.request_headers = headers; + blocked_request.net_log = &request->net_log(); - if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) { + if (blocked_request.num_handlers_blocking == 0) { // If there are no blocking handlers, only the declarative rules tried // to modify the request and we can respond synchronously. return ExecuteDeltas(browser_context, request->identifier(), false /* call_callback*/); - } else { - return net::ERR_IO_PENDING; } + return net::ERR_IO_PENDING; } void ExtensionWebRequestEventRouter::OnSendHeaders( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, const net::HttpRequestHeaders& headers) { - // We hide events from the system context as well as sensitive requests. - if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + if (ShouldHideEvent(browser_context, extension_info_map, request)) return; if (GetAndSetSignaled(request->identifier(), kOnSendHeaders)) @@ -875,10 +884,9 @@ void ExtensionWebRequestEventRouter::OnSendHeaders( ClearSignaled(request->identifier(), kOnBeforeRedirect); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - keys::kOnSendHeadersEvent, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, keys::kOnSendHeadersEvent, request, + &extra_info_spec); if (listeners.empty()) return; @@ -894,15 +902,13 @@ void ExtensionWebRequestEventRouter::OnSendHeaders( int ExtensionWebRequestEventRouter::OnHeadersReceived( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, const net::CompletionCallback& callback, const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url) { - // We hide events from the system context as well as sensitive requests. - if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + if (ShouldHideEvent(browser_context, extension_info_map, request)) return net::OK; bool initialize_blocked_requests = false; @@ -912,10 +918,9 @@ int ExtensionWebRequestEventRouter::OnHeadersReceived( request, ON_HEADERS_RECEIVED, original_response_headers); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - keys::kOnHeadersReceivedEvent, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, keys::kOnHeadersReceivedEvent, + request, &extra_info_spec); if (!listeners.empty() && !GetAndSetSignaled(request->identifier(), kOnHeadersReceived)) { @@ -923,12 +928,12 @@ int ExtensionWebRequestEventRouter::OnHeadersReceived( base::DictionaryValue* dict = new base::DictionaryValue(); ExtractRequestInfo(request, dict); dict->SetString(keys::kStatusLineKey, - original_response_headers->GetStatusLine()); + original_response_headers->GetStatusLine()); dict->SetInteger(keys::kStatusCodeKey, - original_response_headers->response_code()); + original_response_headers->response_code()); if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { dict->Set(keys::kResponseHeadersKey, - GetResponseHeadersList(original_response_headers)); + GetResponseHeadersList(original_response_headers)); } args.Append(dict); @@ -939,33 +944,29 @@ int ExtensionWebRequestEventRouter::OnHeadersReceived( if (!initialize_blocked_requests) return net::OK; // Nobody saw a reason for modifying the request. - blocked_requests_[request->identifier()].event = kOnHeadersReceived; - blocked_requests_[request->identifier()].is_incognito |= - IsIncognitoBrowserContext(browser_context); - blocked_requests_[request->identifier()].request = request; - blocked_requests_[request->identifier()].callback = callback; - blocked_requests_[request->identifier()].net_log = &request->net_log(); - blocked_requests_[request->identifier()].override_response_headers = - override_response_headers; - blocked_requests_[request->identifier()].original_response_headers = - original_response_headers; - blocked_requests_[request->identifier()].new_url = - allowed_unsafe_redirect_url; - - if (blocked_requests_[request->identifier()].num_handlers_blocking == 0) { + BlockedRequest& blocked_request = blocked_requests_[request->identifier()]; + blocked_request.event = kOnHeadersReceived; + blocked_request.is_incognito |= IsIncognitoBrowserContext(browser_context); + blocked_request.request = request; + blocked_request.callback = callback; + blocked_request.net_log = &request->net_log(); + blocked_request.override_response_headers = override_response_headers; + blocked_request.original_response_headers = original_response_headers; + blocked_request.new_url = allowed_unsafe_redirect_url; + + if (blocked_request.num_handlers_blocking == 0) { // If there are no blocking handlers, only the declarative rules tried // to modify the request and we can respond synchronously. return ExecuteDeltas(browser_context, request->identifier(), false /* call_callback*/); - } else { - return net::ERR_IO_PENDING; } + return net::ERR_IO_PENDING; } net::NetworkDelegate::AuthRequiredResponse ExtensionWebRequestEventRouter::OnAuthRequired( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, const net::AuthChallengeInfo& auth_info, const net::NetworkDelegate::AuthCallback& callback, @@ -973,14 +974,14 @@ ExtensionWebRequestEventRouter::OnAuthRequired( // No browser_context means that this is for authentication challenges in the // system context. Skip in that case. Also skip sensitive requests. if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + WebRequestPermissions::HideRequest(extension_info_map, request)) { return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; + } int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - keys::kOnAuthRequiredEvent, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, keys::kOnAuthRequiredEvent, request, + &extra_info_spec); if (listeners.empty()) return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; @@ -997,9 +998,10 @@ ExtensionWebRequestEventRouter::OnAuthRequired( challenger->SetInteger(keys::kPortKey, auth_info.challenger.port()); dict->Set(keys::kChallengerKey, challenger); dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers())); - if (request->response_headers()) + if (request->response_headers()) { dict->SetInteger(keys::kStatusCodeKey, request->response_headers()->response_code()); + } if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { dict->Set(keys::kResponseHeadersKey, GetResponseHeadersList(request->response_headers())); @@ -1007,13 +1009,13 @@ ExtensionWebRequestEventRouter::OnAuthRequired( args.Append(dict); if (DispatchEvent(browser_context, request, listeners, args)) { - blocked_requests_[request->identifier()].event = kOnAuthRequired; - blocked_requests_[request->identifier()].is_incognito |= - IsIncognitoBrowserContext(browser_context); - blocked_requests_[request->identifier()].request = request; - blocked_requests_[request->identifier()].auth_callback = callback; - blocked_requests_[request->identifier()].auth_credentials = credentials; - blocked_requests_[request->identifier()].net_log = &request->net_log(); + BlockedRequest& blocked_request = blocked_requests_[request->identifier()]; + blocked_request.event = kOnAuthRequired; + blocked_request.is_incognito |= IsIncognitoBrowserContext(browser_context); + blocked_request.request = request; + blocked_request.auth_callback = callback; + blocked_request.auth_credentials = credentials; + blocked_request.net_log = &request->net_log(); return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_IO_PENDING; } return net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; @@ -1021,12 +1023,10 @@ ExtensionWebRequestEventRouter::OnAuthRequired( void ExtensionWebRequestEventRouter::OnBeforeRedirect( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, const GURL& new_location) { - // We hide events from the system context as well as sensitive requests. - if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + if (ShouldHideEvent(browser_context, extension_info_map, request)) return; if (GetAndSetSignaled(request->identifier(), kOnBeforeRedirect)) @@ -1038,10 +1038,9 @@ void ExtensionWebRequestEventRouter::OnBeforeRedirect( ClearSignaled(request->identifier(), kOnHeadersReceived); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - keys::kOnBeforeRedirectEvent, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, keys::kOnBeforeRedirectEvent, + request, &extra_info_spec); if (listeners.empty()) return; @@ -1069,11 +1068,9 @@ void ExtensionWebRequestEventRouter::OnBeforeRedirect( void ExtensionWebRequestEventRouter::OnResponseStarted( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request) { - // We hide events from the system context as well as sensitive requests. - if (!browser_context || - WebRequestPermissions::HideRequest(extension_info_map, request)) + if (ShouldHideEvent(browser_context, extension_info_map, request)) return; // OnResponseStarted is even triggered, when the request was cancelled. @@ -1081,18 +1078,12 @@ void ExtensionWebRequestEventRouter::OnResponseStarted( return; int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - keys::kOnResponseStartedEvent, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, keys::kOnResponseStartedEvent, + request, &extra_info_spec); if (listeners.empty()) return; - // UrlRequestFileJobs do not send headers, so we simulate their behavior. - int response_code = 200; - if (request->response_headers()) - response_code = request->response_headers()->response_code(); - std::string response_ip = request->GetSocketAddress().host(); base::ListValue args; @@ -1101,7 +1092,8 @@ void ExtensionWebRequestEventRouter::OnResponseStarted( if (!response_ip.empty()) dict->SetString(keys::kIpKey, response_ip); dict->SetBoolean(keys::kFromCache, request->was_cached()); - dict->SetInteger(keys::kStatusCodeKey, response_code); + dict->SetInteger(keys::kStatusCodeKey, + GetResponseCodeWithDefault(request->response_headers())); dict->Set(keys::kStatusLineKey, GetStatusLine(request->response_headers())); if (extra_info_spec & ExtraInfoSpec::RESPONSE_HEADERS) { dict->Set(keys::kResponseHeadersKey, @@ -1112,17 +1104,19 @@ void ExtensionWebRequestEventRouter::OnResponseStarted( DispatchEvent(browser_context, request, listeners, args); } -void ExtensionWebRequestEventRouter::OnCompleted(void* browser_context, - InfoMap* extension_info_map, - net::URLRequest* request) { +void ExtensionWebRequestEventRouter::OnCompleted( + void* browser_context, + const InfoMap* extension_info_map, + net::URLRequest* request) { // We hide events from the system context as well as sensitive requests. // However, if the request first became sensitive after redirecting we have // already signaled it and thus we have to signal the end of it. This is // risk-free because the handler cannot modify the request now. if (!browser_context || (WebRequestPermissions::HideRequest(extension_info_map, request) && - !WasSignaled(*request))) + !WasSignaled(*request))) { return; + } request_time_tracker_->LogRequestEndTime(request->identifier(), base::Time::Now()); @@ -1134,23 +1128,19 @@ void ExtensionWebRequestEventRouter::OnCompleted(void* browser_context, ClearPendingCallbacks(request); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = + EventListeners listeners = GetMatchingListeners(browser_context, extension_info_map, keys::kOnCompletedEvent, request, &extra_info_spec); if (listeners.empty()) return; - // UrlRequestFileJobs do not send headers, so we simulate their behavior. - int response_code = 200; - if (request->response_headers()) - response_code = request->response_headers()->response_code(); - std::string response_ip = request->GetSocketAddress().host(); base::ListValue args; base::DictionaryValue* dict = new base::DictionaryValue(); ExtractRequestInfo(request, dict); - dict->SetInteger(keys::kStatusCodeKey, response_code); + dict->SetInteger(keys::kStatusCodeKey, + GetResponseCodeWithDefault(request->response_headers())); if (!response_ip.empty()) dict->SetString(keys::kIpKey, response_ip); dict->SetBoolean(keys::kFromCache, request->was_cached()); @@ -1166,7 +1156,7 @@ void ExtensionWebRequestEventRouter::OnCompleted(void* browser_context, void ExtensionWebRequestEventRouter::OnErrorOccurred( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, net::URLRequest* request, bool started) { // We hide events from the system context as well as sensitive requests. @@ -1175,8 +1165,9 @@ void ExtensionWebRequestEventRouter::OnErrorOccurred( // risk-free because the handler cannot modify the request now. if (!browser_context || (WebRequestPermissions::HideRequest(extension_info_map, request) && - !WasSignaled(*request))) + !WasSignaled(*request))) { return; + } request_time_tracker_->LogRequestEndTime(request->identifier(), base::Time::Now()); @@ -1189,10 +1180,9 @@ void ExtensionWebRequestEventRouter::OnErrorOccurred( ClearPendingCallbacks(request); int extra_info_spec = 0; - std::vector<const EventListener*> listeners = - GetMatchingListeners(browser_context, extension_info_map, - web_request::OnErrorOccurred::kEventName, request, - &extra_info_spec); + EventListeners listeners = GetMatchingListeners( + browser_context, extension_info_map, + web_request::OnErrorOccurred::kEventName, request, &extra_info_spec); if (listeners.empty()) return; @@ -1213,7 +1203,8 @@ void ExtensionWebRequestEventRouter::OnErrorOccurred( } void ExtensionWebRequestEventRouter::OnURLRequestDestroyed( - void* browser_context, net::URLRequest* request) { + void* browser_context, + const net::URLRequest* request) { ClearPendingCallbacks(request); signaled_requests_.erase(request->identifier()); @@ -1223,7 +1214,7 @@ void ExtensionWebRequestEventRouter::OnURLRequestDestroyed( } void ExtensionWebRequestEventRouter::ClearPendingCallbacks( - net::URLRequest* request) { + const net::URLRequest* request) { blocked_requests_.erase(request->identifier()); } @@ -1268,13 +1259,11 @@ bool ExtensionWebRequestEventRouter::DispatchEvent( } if (num_handlers_blocking > 0) { - blocked_requests_[request->identifier()].request = request; - blocked_requests_[request->identifier()].is_incognito |= - IsIncognitoBrowserContext(browser_context); - blocked_requests_[request->identifier()].num_handlers_blocking += - num_handlers_blocking; - blocked_requests_[request->identifier()].blocking_time = base::Time::Now(); - + BlockedRequest& blocked_request = blocked_requests_[request->identifier()]; + blocked_request.request = request; + blocked_request.is_incognito |= IsIncognitoBrowserContext(browser_context); + blocked_request.num_handlers_blocking += num_handlers_blocking; + blocked_request.blocking_time = base::Time::Now(); return true; } @@ -1286,7 +1275,7 @@ void ExtensionWebRequestEventRouter::OnEventHandled( const std::string& extension_id, const std::string& event_name, const std::string& sub_event_name, - uint64 request_id, + uint64_t request_id, EventResponse* response) { // TODO(robwu): Does this also work with webviews? operator< (used by find) // takes the webview ID into account, which is not set on |listener|. @@ -1335,7 +1324,7 @@ bool ExtensionWebRequestEventRouter::AddEventListener( base::UserMetricsAction("WebView.WebRequest.AddListener")); } - if (listeners_[browser_context][event_name].count(listener) != 0u) { + if (ContainsKey(listeners_[browser_context][event_name], listener)) { // This is likely an abuse of the API by a malicious extension. return false; } @@ -1363,18 +1352,16 @@ void ExtensionWebRequestEventRouter::RemoveEventListener( // It's possible for AddEventListener to fail asynchronously. In that case, // the renderer believes the listener exists, while the browser does not. // Ignore a RemoveEventListener in that case. - std::set<EventListener>::iterator found = event_listeners.find(listener); - if (found == event_listeners.end()) + std::set<EventListener>::const_iterator it = event_listeners.find(listener); + if (it == event_listeners.end()) return; CHECK_EQ(event_listeners.count(listener), 1u) << "extension=" << extension_id << " event=" << event_name; // Unblock any request that this event listener may have been blocking. - for (std::set<uint64>::iterator it = found->blocked_requests.begin(); - it != found->blocked_requests.end(); ++it) { - DecrementBlockCount(browser_context, extension_id, event_name, *it, NULL); - } + for (uint64_t id : it->blocked_requests) + DecrementBlockCount(browser_context, extension_id, event_name, id, NULL); event_listeners.erase(listener); @@ -1434,7 +1421,7 @@ void ExtensionWebRequestEventRouter::AddCallbackForPageLoad( } bool ExtensionWebRequestEventRouter::IsPageLoad( - net::URLRequest* request) const { + const net::URLRequest* request) const { bool is_main_frame = false; int frame_id = -1; bool parent_is_main_frame = false; @@ -1452,11 +1439,8 @@ bool ExtensionWebRequestEventRouter::IsPageLoad( } void ExtensionWebRequestEventRouter::NotifyPageLoad() { - for (CallbacksForPageLoad::const_iterator i = - callbacks_for_page_load_.begin(); - i != callbacks_for_page_load_.end(); ++i) { - i->Run(); - } + for (const auto& callback : callbacks_for_page_load_) + callback.Run(); callbacks_for_page_load_.clear(); } @@ -1487,8 +1471,8 @@ bool ExtensionWebRequestEventRouter::WasSignaled( void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( void* browser_context, - net::URLRequest* request, - InfoMap* extension_info_map, + const net::URLRequest* request, + const InfoMap* extension_info_map, bool crosses_incognito, const std::string& event_name, const GURL& url, @@ -1498,8 +1482,7 @@ void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( bool is_async_request, bool is_request_from_extension, int* extra_info_spec, - std::vector<const ExtensionWebRequestEventRouter::EventListener*>* - matching_listeners) { + EventListeners* matching_listeners) { std::string web_request_event_name(event_name); WebViewRendererState::WebViewInfo web_view_info; bool is_web_view_guest = WebViewRendererState::GetInstance()->GetInfo( @@ -1511,44 +1494,53 @@ void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( std::set<EventListener>& listeners = listeners_[browser_context][web_request_event_name]; - for (std::set<EventListener>::iterator it = listeners.begin(); - it != listeners.end(); ++it) { - if (!it->ipc_sender.get()) { + for (const EventListener& listener : listeners) { + if (!listener.ipc_sender.get()) { // The IPC sender has been deleted. This listener will be removed soon // via a call to RemoveEventListener. For now, just skip it. continue; } if (is_web_view_guest && - (it->embedder_process_id != web_view_info.embedder_process_id || - it->web_view_instance_id != web_view_info.instance_id)) + (listener.embedder_process_id != web_view_info.embedder_process_id || + listener.web_view_instance_id != web_view_info.instance_id)) { continue; + } // Filter requests from other extensions / apps. This does not work for // content scripts, or extension pages in non-extension processes. if (is_request_from_extension && - it->embedder_process_id != render_process_host_id) + listener.embedder_process_id != render_process_host_id) { continue; + } - if (!it->filter.urls.is_empty() && !it->filter.urls.MatchesURL(url)) + if (!listener.filter.urls.is_empty() && + !listener.filter.urls.MatchesURL(url)) { continue; + } + if (web_request_event_router_delegate_ && web_request_event_router_delegate_->OnGetMatchingListenersImplCheck( - it->filter.tab_id, it->filter.window_id, request)) + listener.filter.tab_id, listener.filter.window_id, request)) { continue; - if (!it->filter.types.empty() && - std::find(it->filter.types.begin(), it->filter.types.end(), - resource_type) == it->filter.types.end()) + } + + const std::vector<content::ResourceType>& types = listener.filter.types; + if (!types.empty() && + std::find(types.begin(), types.end(), resource_type) == types.end()) { continue; + } - if (!is_web_view_guest && !WebRequestPermissions::CanExtensionAccessURL( - extension_info_map, it->extension_id, url, crosses_incognito, - WebRequestPermissions::REQUIRE_HOST_PERMISSION)) + if (!is_web_view_guest && + !WebRequestPermissions::CanExtensionAccessURL( + extension_info_map, listener.extension_id, url, crosses_incognito, + WebRequestPermissions::REQUIRE_HOST_PERMISSION)) { continue; + } bool blocking_listener = - (it->extra_info_spec & - (ExtraInfoSpec::BLOCKING | ExtraInfoSpec::ASYNC_BLOCKING)) != 0; + (listener.extra_info_spec & + (ExtraInfoSpec::BLOCKING | ExtraInfoSpec::ASYNC_BLOCKING)) != 0; // We do not want to notify extensions about XHR requests that are // triggered by themselves. This is a workaround to prevent deadlocks @@ -1564,17 +1556,17 @@ void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( if (blocking_listener && synchronous_xhr_from_extension) continue; - matching_listeners->push_back(&(*it)); - *extra_info_spec |= it->extra_info_spec; + matching_listeners->push_back(&listener); + *extra_info_spec |= listener.extra_info_spec; } } -std::vector<const ExtensionWebRequestEventRouter::EventListener*> +ExtensionWebRequestEventRouter::EventListeners ExtensionWebRequestEventRouter::GetMatchingListeners( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, const std::string& event_name, - net::URLRequest* request, + const net::URLRequest* request, int* extra_info_spec) { // TODO(mpcomplete): handle browser_context == NULL (should collect all // listeners). @@ -1594,9 +1586,6 @@ ExtensionWebRequestEventRouter::GetMatchingListeners( &render_process_host_id, &routing_id, &resource_type); - std::vector<const ExtensionWebRequestEventRouter::EventListener*> - matching_listeners; - bool is_request_from_extension = IsRequestFromExtension(request, extension_info_map); @@ -1605,6 +1594,7 @@ ExtensionWebRequestEventRouter::GetMatchingListeners( // we don't have an info object. We don't want to risk a deadlock. bool is_async_request = !info || info->IsAsync(); + EventListeners matching_listeners; GetMatchingListenersImpl( browser_context, request, extension_info_map, false, event_name, url, render_process_host_id, routing_id, resource_type, @@ -1658,17 +1648,15 @@ helpers::EventResponseDelta* CalculateDelta( response->cancel, &response->auth_credentials); default: NOTREACHED(); - break; + return nullptr; } - return NULL; } base::Value* SerializeResponseHeaders(const helpers::ResponseHeaders& headers) { scoped_ptr<base::ListValue> serialized_headers(new base::ListValue()); - for (helpers::ResponseHeaders::const_iterator i = headers.begin(); - i != headers.end(); ++i) { + for (const auto& it : headers) { serialized_headers->Append( - helpers::CreateHeaderDictionary(i->first, i->second)); + helpers::CreateHeaderDictionary(it.first, it.second)); } return serialized_headers.release(); } @@ -1677,15 +1665,13 @@ base::Value* SerializeResponseHeaders(const helpers::ResponseHeaders& headers) { // base::ListValue which summarizes the changes made. This is templated since // the two types (request/response) are different but contain essentially the // same fields. -template<typename CookieType> +template <typename CookieType> base::ListValue* SummarizeCookieModifications( - const std::vector<linked_ptr<CookieType> >& modifications) { + const std::vector<linked_ptr<CookieType>>& modifications) { scoped_ptr<base::ListValue> cookie_modifications(new base::ListValue()); - for (typename std::vector<linked_ptr<CookieType> >::const_iterator i = - modifications.begin(); - i != modifications.end(); ++i) { + for (const auto& it : modifications) { scoped_ptr<base::DictionaryValue> summary(new base::DictionaryValue()); - const CookieType& mod = *i->get(); + const CookieType& mod = *(it.get()); switch (mod.type) { case helpers::ADD: summary->SetString(activity_log::kCookieModificationTypeKey, @@ -1701,20 +1687,24 @@ base::ListValue* SummarizeCookieModifications( break; } if (mod.filter) { - if (mod.filter->name) + if (mod.filter->name) { summary->SetString(activity_log::kCookieFilterNameKey, *mod.modification->name); - if (mod.filter->domain) + } + if (mod.filter->domain) { summary->SetString(activity_log::kCookieFilterDomainKey, *mod.modification->name); + } } if (mod.modification) { - if (mod.modification->name) + if (mod.modification->name) { summary->SetString(activity_log::kCookieModDomainKey, *mod.modification->name); - if (mod.modification->domain) + } + if (mod.modification->domain) { summary->SetString(activity_log::kCookieModDomainKey, *mod.modification->name); + } } cookie_modifications->Append(summary.release()); } @@ -1727,12 +1717,10 @@ scoped_ptr<base::DictionaryValue> SummarizeResponseDelta( const std::string& event_name, const helpers::EventResponseDelta& delta) { scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue()); - if (delta.cancel) { + if (delta.cancel) details->SetBoolean(activity_log::kCancelKey, true); - } - if (!delta.new_url.is_empty()) { + if (!delta.new_url.is_empty()) details->SetString(activity_log::kNewUrlKey, delta.new_url.spec()); - } scoped_ptr<base::ListValue> modified_headers(new base::ListValue()); net::HttpRequestHeaders::Iterator iter(delta.modified_request_headers); @@ -1809,16 +1797,17 @@ void ExtensionWebRequestEventRouter::DecrementBlockCount( void* browser_context, const std::string& extension_id, const std::string& event_name, - uint64 request_id, + uint64_t request_id, EventResponse* response) { scoped_ptr<EventResponse> response_scoped(response); // It's possible that this request was deleted, or cancelled by a previous // event handler. If so, ignore this response. - if (blocked_requests_.find(request_id) == blocked_requests_.end()) + auto it = blocked_requests_.find(request_id); + if (it == blocked_requests_.end()) return; - BlockedRequest& blocked_request = blocked_requests_[request_id]; + BlockedRequest& blocked_request = it->second; int num_handlers_blocking = --blocked_request.num_handlers_blocking; CHECK_GE(num_handlers_blocking, 0); @@ -1857,13 +1846,12 @@ void ExtensionWebRequestEventRouter::DecrementBlockCount( std::set<EventListener>& listeners = listeners_[browser_context][event_name]; - for (std::set<EventListener>::iterator it = listeners.begin(); - it != listeners.end(); ++it) { - if (it->blocked_requests.count(request_id) == 0) + for (const auto& listener : listeners) { + if (!ContainsKey(listener.blocked_requests, request_id)) continue; std::string delegate_info = l10n_util::GetStringFUTF8(IDS_LOAD_STATE_PARAMETER_EXTENSION, - base::UTF8ToUTF16(it->extension_name)); + base::UTF8ToUTF16(listener.extension_name)); blocked_request.request->LogAndReportBlockedBy(delegate_info.c_str()); break; } @@ -1874,39 +1862,32 @@ void ExtensionWebRequestEventRouter::SendMessages( void* browser_context, const BlockedRequest& blocked_request) { const helpers::EventResponseDeltas& deltas = blocked_request.response_deltas; - for (helpers::EventResponseDeltas::const_iterator delta = deltas.begin(); - delta != deltas.end(); ++delta) { - const std::set<std::string>& messages = (*delta)->messages_to_extension; - for (std::set<std::string>::const_iterator message = messages.begin(); - message != messages.end(); ++message) { + for (const auto& delta : deltas) { + const std::set<std::string>& messages = delta->messages_to_extension; + for (const std::string& message : messages) { scoped_ptr<base::DictionaryValue> argument(new base::DictionaryValue); ExtractRequestInfo(blocked_request.request, argument.get()); WebViewRendererState::WebViewInfo web_view_info; bool is_web_view_guest = GetWebViewInfo(blocked_request.request, &web_view_info); - argument->SetString(keys::kMessageKey, *message); + argument->SetString(keys::kMessageKey, message); argument->SetString(keys::kStageKey, GetRequestStageAsString(blocked_request.event)); BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - base::Bind(&SendOnMessageEventOnUI, - browser_context, - (*delta)->extension_id, - is_web_view_guest, - web_view_info, + BrowserThread::UI, FROM_HERE, + base::Bind(&SendOnMessageEventOnUI, browser_context, + delta->extension_id, is_web_view_guest, web_view_info, base::Passed(&argument))); } } } -int ExtensionWebRequestEventRouter::ExecuteDeltas( - void* browser_context, - uint64 request_id, - bool call_callback) { +int ExtensionWebRequestEventRouter::ExecuteDeltas(void* browser_context, + uint64_t request_id, + bool call_callback) { BlockedRequest& blocked_request = blocked_requests_[request_id]; - CHECK(blocked_request.num_handlers_blocking == 0); + CHECK_EQ(0, blocked_request.num_handlers_blocking); helpers::EventResponseDeltas& deltas = blocked_request.response_deltas; base::TimeDelta block_time = base::Time::Now() - blocked_request.blocking_time; @@ -1915,14 +1896,12 @@ int ExtensionWebRequestEventRouter::ExecuteDeltas( bool credentials_set = false; deltas.sort(&helpers::InDecreasingExtensionInstallationTimeOrder); - WarningSet warnings; bool canceled = false; - helpers::MergeCancelOfResponses( - blocked_request.response_deltas, - &canceled, - blocked_request.net_log); + helpers::MergeCancelOfResponses(blocked_request.response_deltas, &canceled, + blocked_request.net_log); + WarningSet warnings; if (blocked_request.event == kOnBeforeRequest) { CHECK(!blocked_request.callback.is_null()); helpers::MergeOnBeforeRequestResponses( @@ -1986,13 +1965,14 @@ int ExtensionWebRequestEventRouter::ExecuteDeltas( if (call_callback) callback.Run(rv); } else if (!blocked_request.auth_callback.is_null()) { - net::NetworkDelegate::AuthRequiredResponse response = - net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; - if (canceled) { + net::NetworkDelegate::AuthRequiredResponse response; + if (canceled) response = net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH; - } else if (credentials_set) { + else if (credentials_set) response = net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH; - } + else + response = net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; + net::NetworkDelegate::AuthCallback callback = blocked_request.auth_callback; blocked_requests_.erase(request_id); if (call_callback) @@ -2005,7 +1985,7 @@ int ExtensionWebRequestEventRouter::ExecuteDeltas( bool ExtensionWebRequestEventRouter::ProcessDeclarativeRules( void* browser_context, - InfoMap* extension_info_map, + const InfoMap* extension_info_map, const std::string& event_name, net::URLRequest* request, RequestStage request_stage, @@ -2027,66 +2007,57 @@ bool ExtensionWebRequestEventRouter::ProcessDeclarativeRules( // First parameter identifies the registry, the second indicates whether the // registry belongs to the cross browser_context. - typedef std::pair<WebRequestRulesRegistry*, bool> RelevantRegistry; - typedef std::vector<RelevantRegistry> RelevantRegistries; - RelevantRegistries relevant_registries; + using RelevantRegistry = std::pair<WebRequestRulesRegistry*, bool>; + std::vector<RelevantRegistry> relevant_registries; - if (rules_registries_.find(rules_key) != rules_registries_.end()) { + auto rules_key_it = rules_registries_.find(rules_key); + if (rules_key_it != rules_registries_.end()) { relevant_registries.push_back( - std::make_pair(rules_registries_[rules_key].get(), false)); + std::make_pair(rules_key_it->second.get(), false)); } void* cross_browser_context = GetCrossBrowserContext(browser_context); RulesRegistryKey cross_browser_context_rules_key(cross_browser_context, rules_registry_id); - if (cross_browser_context && - rules_registries_.find(cross_browser_context_rules_key) != - rules_registries_.end()) { - relevant_registries.push_back( - std::make_pair( - rules_registries_[cross_browser_context_rules_key].get(), true)); + if (cross_browser_context) { + auto it = rules_registries_.find(cross_browser_context_rules_key); + if (it != rules_registries_.end()) + relevant_registries.push_back(std::make_pair(it->second.get(), true)); } // The following block is experimentally enabled and its impact on load time // logged with UMA Extensions.NetworkDelayRegistryLoad. crbug.com/175961 - for (RelevantRegistries::iterator i = relevant_registries.begin(); - i != relevant_registries.end(); ++i) { - WebRequestRulesRegistry* rules_registry = i->first; - if (!rules_registry->ready().is_signaled()) { - // The rules registry is still loading. Block this request until it - // finishes. - rules_registry->ready().Post( - FROM_HERE, - base::Bind(&ExtensionWebRequestEventRouter::OnRulesRegistryReady, - AsWeakPtr(), - browser_context, - event_name, - request->identifier(), - request_stage)); - blocked_requests_[request->identifier()].num_handlers_blocking++; - blocked_requests_[request->identifier()].request = request; - blocked_requests_[request->identifier()].is_incognito |= - IsIncognitoBrowserContext(browser_context); - blocked_requests_[request->identifier()].blocking_time = - base::Time::Now(); - blocked_requests_[request->identifier()].original_response_headers = - original_response_headers; - blocked_requests_[request->identifier()].extension_info_map = - extension_info_map; - return true; - } + for (auto it : relevant_registries) { + WebRequestRulesRegistry* rules_registry = it.first; + if (rules_registry->ready().is_signaled()) + continue; + + // The rules registry is still loading. Block this request until it + // finishes. + rules_registry->ready().Post( + FROM_HERE, + base::Bind(&ExtensionWebRequestEventRouter::OnRulesRegistryReady, + AsWeakPtr(), browser_context, event_name, + request->identifier(), request_stage)); + BlockedRequest& blocked_request = blocked_requests_[request->identifier()]; + blocked_request.num_handlers_blocking++; + blocked_request.request = request; + blocked_request.is_incognito |= IsIncognitoBrowserContext(browser_context); + blocked_request.blocking_time = base::Time::Now(); + blocked_request.original_response_headers = original_response_headers; + blocked_request.extension_info_map = extension_info_map; + return true; } base::Time start = base::Time::Now(); bool deltas_created = false; - for (RelevantRegistries::iterator i = relevant_registries.begin(); - i != relevant_registries.end(); ++i) { - WebRequestRulesRegistry* rules_registry = i->first; + for (const auto& it : relevant_registries) { + WebRequestRulesRegistry* rules_registry = it.first; helpers::EventResponseDeltas result = rules_registry->CreateDeltas( extension_info_map, WebRequestData(request, request_stage, original_response_headers), - i->second); + it.second); if (!result.empty()) { helpers::EventResponseDeltas& deltas = @@ -2106,14 +2077,15 @@ bool ExtensionWebRequestEventRouter::ProcessDeclarativeRules( void ExtensionWebRequestEventRouter::OnRulesRegistryReady( void* browser_context, const std::string& event_name, - uint64 request_id, + uint64_t request_id, RequestStage request_stage) { // It's possible that this request was deleted, or cancelled by a previous // event handler. If so, ignore this response. - if (blocked_requests_.find(request_id) == blocked_requests_.end()) + auto it = blocked_requests_.find(request_id); + if (it == blocked_requests_.end()) return; - BlockedRequest& blocked_request = blocked_requests_[request_id]; + BlockedRequest& blocked_request = it->second; base::TimeDelta block_time = base::Time::Now() - blocked_request.blocking_time; UMA_HISTOGRAM_TIMES("Extensions.NetworkDelayRegistryLoad", block_time); @@ -2130,7 +2102,7 @@ void ExtensionWebRequestEventRouter::OnRulesRegistryReady( browser_context, std::string(), event_name, request_id, NULL); } -bool ExtensionWebRequestEventRouter::GetAndSetSignaled(uint64 request_id, +bool ExtensionWebRequestEventRouter::GetAndSetSignaled(uint64_t request_id, EventTypes event_type) { SignaledRequestMap::iterator iter = signaled_requests_.find(request_id); if (iter == signaled_requests_.end()) { @@ -2142,7 +2114,7 @@ bool ExtensionWebRequestEventRouter::GetAndSetSignaled(uint64 request_id, return was_signaled_before; } -void ExtensionWebRequestEventRouter::ClearSignaled(uint64 request_id, +void ExtensionWebRequestEventRouter::ClearSignaled(uint64_t request_id, EventTypes event_type) { SignaledRequestMap::iterator iter = signaled_requests_.find(request_id); if (iter == signaled_requests_.end()) @@ -2306,7 +2278,7 @@ bool WebRequestInternalAddEventListenerFunction::RunSync() { void WebRequestInternalEventHandledFunction::RespondWithError( const std::string& event_name, const std::string& sub_event_name, - uint64 request_id, + uint64_t request_id, scoped_ptr<ExtensionWebRequestEventRouter::EventResponse> response, const std::string& error) { error_ = error; @@ -2328,7 +2300,7 @@ bool WebRequestInternalEventHandledFunction::RunSync() { std::string request_id_str; EXTENSION_FUNCTION_VALIDATE(args_->GetString(2, &request_id_str)); - uint64 request_id; + uint64_t request_id; EXTENSION_FUNCTION_VALIDATE(base::StringToUint64(request_id_str, &request_id)); @@ -2376,10 +2348,10 @@ bool WebRequestInternalEventHandledFunction::RunSync() { } } - const bool hasRequestHeaders = value->HasKey("requestHeaders"); - const bool hasResponseHeaders = value->HasKey("responseHeaders"); - if (hasRequestHeaders || hasResponseHeaders) { - if (hasRequestHeaders && hasResponseHeaders) { + const bool has_request_headers = value->HasKey("requestHeaders"); + const bool has_response_headers = value->HasKey("responseHeaders"); + if (has_request_headers || has_response_headers) { + if (has_request_headers && has_response_headers) { // Allow only one of the keys, not both. RespondWithError(event_name, sub_event_name, @@ -2392,7 +2364,7 @@ bool WebRequestInternalEventHandledFunction::RunSync() { base::ListValue* headers_value = NULL; scoped_ptr<net::HttpRequestHeaders> request_headers; scoped_ptr<helpers::ResponseHeaders> response_headers; - if (hasRequestHeaders) { + if (has_request_headers) { request_headers.reset(new net::HttpRequestHeaders()); EXTENSION_FUNCTION_VALIDATE(value->GetList(keys::kRequestHeadersKey, &headers_value)); @@ -2436,12 +2408,12 @@ bool WebRequestInternalEventHandledFunction::RunSync() { keys::kInvalidHeaderValue, name)); return false; } - if (hasRequestHeaders) + if (has_request_headers) request_headers->SetHeader(name, value); else response_headers->push_back(helpers::ResponseHeader(name, value)); } - if (hasRequestHeaders) + if (has_request_headers) response->request_headers.reset(request_headers.release()); else response->response_headers.reset(response_headers.release()); diff --git a/extensions/browser/api/web_request/web_request_api.h b/extensions/browser/api/web_request/web_request_api.h index 06ffbff..2b262aa 100644 --- a/extensions/browser/api/web_request/web_request_api.h +++ b/extensions/browser/api/web_request/web_request_api.h @@ -9,6 +9,7 @@ #include <map> #include <set> #include <string> +#include <utility> #include <vector> #include "base/memory/singleton.h" @@ -43,8 +44,8 @@ class BrowserContext; } namespace net { -class AuthCredentials; class AuthChallengeInfo; +class AuthCredentials; class HttpRequestHeaders; class HttpResponseHeaders; class URLRequest; @@ -162,6 +163,7 @@ class ExtensionWebRequestEventRouter scoped_ptr<net::AuthCredentials> auth_credentials; + private: DISALLOW_COPY_AND_ASSIGN(EventResponse); }; @@ -178,7 +180,7 @@ class ExtensionWebRequestEventRouter // the given request. Returns net::ERR_IO_PENDING if an extension is // intercepting the request, OK otherwise. int OnBeforeRequest(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, const net::CompletionCallback& callback, GURL* new_url); @@ -188,7 +190,7 @@ class ExtensionWebRequestEventRouter // Returns net::ERR_IO_PENDING if an extension is intercepting the request, OK // otherwise. int OnBeforeSendHeaders(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, const net::CompletionCallback& callback, net::HttpRequestHeaders* headers); @@ -196,7 +198,7 @@ class ExtensionWebRequestEventRouter // Dispatches the onSendHeaders event. This is fired for HTTP(s) requests // only. void OnSendHeaders(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, const net::HttpRequestHeaders& headers); @@ -211,7 +213,7 @@ class ExtensionWebRequestEventRouter // into |override_response_headers|. int OnHeadersReceived( void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, const net::CompletionCallback& callback, const net::HttpResponseHeaders* original_response_headers, @@ -225,7 +227,7 @@ class ExtensionWebRequestEventRouter // invoked later. net::NetworkDelegate::AuthRequiredResponse OnAuthRequired( void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, const net::AuthChallengeInfo& auth_info, const net::NetworkDelegate::AuthCallback& callback, @@ -234,38 +236,38 @@ class ExtensionWebRequestEventRouter // Dispatches the onBeforeRedirect event. This is fired for HTTP(s) requests // only. void OnBeforeRedirect(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, const GURL& new_location); // Dispatches the onResponseStarted event indicating that the first bytes of // the response have arrived. void OnResponseStarted(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request); // Dispatches the onComplete event. void OnCompleted(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request); // Dispatches an onErrorOccurred event. void OnErrorOccurred(void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, net::URLRequest* request, bool started); // Notifications when objects are going away. - void OnURLRequestDestroyed(void* browser_context, net::URLRequest* request); + void OnURLRequestDestroyed(void* browser_context, + const net::URLRequest* request); // Called when an event listener handles a blocking event and responds. - void OnEventHandled( - void* browser_context, - const std::string& extension_id, - const std::string& event_name, - const std::string& sub_event_name, - uint64 request_id, - EventResponse* response); + void OnEventHandled(void* browser_context, + const std::string& extension_id, + const std::string& event_name, + const std::string& sub_event_name, + uint64_t request_id, + EventResponse* response); // Adds a listener to the given event. |event_name| specifies the event being // listened to. |sub_event_name| is an internal event uniquely generated in @@ -311,24 +313,25 @@ class ExtensionWebRequestEventRouter friend struct DefaultSingletonTraits<ExtensionWebRequestEventRouter>; struct EventListener; - typedef std::map<std::string, std::set<EventListener> > - ListenerMapForBrowserContext; - typedef std::map<void*, ListenerMapForBrowserContext> ListenerMap; - typedef std::map<uint64, BlockedRequest> BlockedRequestMap; + using EventListeners = std::vector<const EventListener*>; + using ListenerMapForBrowserContext = + std::map<std::string, std::set<EventListener>>; + using ListenerMap = std::map<void*, ListenerMapForBrowserContext>; + using BlockedRequestMap = std::map<uint64_t, BlockedRequest>; // Map of request_id -> bit vector of EventTypes already signaled - typedef std::map<uint64, int> SignaledRequestMap; + using SignaledRequestMap = std::map<uint64_t, int>; // For each browser_context: a bool indicating whether it is an incognito // browser_context, and a pointer to the corresponding (non-)incognito // browser_context. - typedef std::map<void*, std::pair<bool, void*> > CrossBrowserContextMap; - typedef std::list<base::Closure> CallbacksForPageLoad; + using CrossBrowserContextMap = std::map<void*, std::pair<bool, void*>>; + using CallbacksForPageLoad = std::list<base::Closure>; ExtensionWebRequestEventRouter(); ~ExtensionWebRequestEventRouter(); // Ensures that future callbacks for |request| are ignored so that it can be // destroyed safely. - void ClearPendingCallbacks(net::URLRequest* request); + void ClearPendingCallbacks(const net::URLRequest* request); bool DispatchEvent( void* browser_context, @@ -341,9 +344,9 @@ class ExtensionWebRequestEventRouter // set of extra_info_spec flags that every matching listener asked for. std::vector<const EventListener*> GetMatchingListeners( void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, const std::string& event_name, - net::URLRequest* request, + const net::URLRequest* request, int* extra_info_spec); // Helper for the above functions. This is called twice: once for the @@ -352,8 +355,8 @@ class ExtensionWebRequestEventRouter // normal browser_context, or vice versa). void GetMatchingListenersImpl( void* browser_context, - net::URLRequest* request, - extensions::InfoMap* extension_info_map, + const net::URLRequest* request, + const extensions::InfoMap* extension_info_map, bool crosses_incognito, const std::string& event_name, const GURL& url, @@ -363,20 +366,18 @@ class ExtensionWebRequestEventRouter bool is_async_request, bool is_request_from_extension, int* extra_info_spec, - std::vector<const ExtensionWebRequestEventRouter::EventListener*>* - matching_listeners); + std::vector<const EventListener*>* matching_listeners); // Decrements the count of event handlers blocking the given request. When the // count reaches 0, we stop blocking the request and proceed it using the // method requested by the extension with the highest precedence. Precedence // is decided by extension install time. If |response| is non-NULL, this // method assumes ownership. - void DecrementBlockCount( - void* browser_context, - const std::string& extension_id, - const std::string& event_name, - uint64 request_id, - EventResponse* response); + void DecrementBlockCount(void* browser_context, + const std::string& extension_id, + const std::string& event_name, + uint64_t request_id, + EventResponse* response); // Logs an extension action. void LogExtensionActivity( @@ -393,8 +394,9 @@ class ExtensionWebRequestEventRouter // The function returns the error code for the network request. This is // mostly relevant in case the caller passes |call_callback| = false // and wants to return the correct network error code himself. - int ExecuteDeltas( - void* browser_context, uint64 request_id, bool call_callback); + int ExecuteDeltas(void* browser_context, + uint64_t request_id, + bool call_callback); // Evaluates the rules of the declarative webrequest API and stores // modifications to the request that result from WebRequestActions as @@ -403,7 +405,7 @@ class ExtensionWebRequestEventRouter // deltas were generated. bool ProcessDeclarativeRules( void* browser_context, - extensions::InfoMap* extension_info_map, + const extensions::InfoMap* extension_info_map, const std::string& event_name, net::URLRequest* request, extensions::RequestStage request_stage, @@ -417,26 +419,26 @@ class ExtensionWebRequestEventRouter // Called when the RulesRegistry is ready to unblock a request that was // waiting for said event. - void OnRulesRegistryReady( - void* browser_context, - const std::string& event_name, - uint64 request_id, - extensions::RequestStage request_stage); + void OnRulesRegistryReady(void* browser_context, + const std::string& event_name, + uint64_t request_id, + extensions::RequestStage request_stage); // Extracts from |request| information for the keys requestId, url, method, // frameId, tabId, type, and timeStamp and writes these into |out| to be // passed on to extensions. - void ExtractRequestInfo(net::URLRequest* request, base::DictionaryValue* out); + void ExtractRequestInfo(const net::URLRequest* request, + base::DictionaryValue* out); // Sets the flag that |event_type| has been signaled for |request_id|. // Returns the value of the flag before setting it. - bool GetAndSetSignaled(uint64 request_id, EventTypes event_type); + bool GetAndSetSignaled(uint64_t request_id, EventTypes event_type); // Clears the flag that |event_type| has been signaled for |request_id|. - void ClearSignaled(uint64 request_id, EventTypes event_type); + void ClearSignaled(uint64_t request_id, EventTypes event_type); // Returns whether |request| represents a top level window navigation. - bool IsPageLoad(net::URLRequest* request) const; + bool IsPageLoad(const net::URLRequest* request) const; // Called on a page load to process all registered callbacks. void NotifyPageLoad(); @@ -528,7 +530,7 @@ class WebRequestInternalEventHandledFunction void RespondWithError( const std::string& event_name, const std::string& sub_event_name, - uint64 request_id, + uint64_t request_id, scoped_ptr<ExtensionWebRequestEventRouter::EventResponse> response, const std::string& error); diff --git a/extensions/browser/api/web_request/web_request_event_router_delegate.cc b/extensions/browser/api/web_request/web_request_event_router_delegate.cc index 54ff080..794e582 100644 --- a/extensions/browser/api/web_request/web_request_event_router_delegate.cc +++ b/extensions/browser/api/web_request/web_request_event_router_delegate.cc @@ -16,12 +16,15 @@ WebRequestEventRouterDelegate::WebRequestEventRouterDelegate() { WebRequestEventRouterDelegate::~WebRequestEventRouterDelegate() { } void WebRequestEventRouterDelegate::ExtractExtraRequestDetails( - net::URLRequest* request, base::DictionaryValue* out){ + const net::URLRequest* request, + base::DictionaryValue* out) { out->SetInteger(keys::kTabIdKey, -1); } bool WebRequestEventRouterDelegate::OnGetMatchingListenersImplCheck( - int tab_id, int window_id, net::URLRequest* request) { + int tab_id, + int window_id, + const net::URLRequest* request) { return false; } diff --git a/extensions/browser/api/web_request/web_request_event_router_delegate.h b/extensions/browser/api/web_request/web_request_event_router_delegate.h index 7ed2614..49e30fe 100644 --- a/extensions/browser/api/web_request/web_request_event_router_delegate.h +++ b/extensions/browser/api/web_request/web_request_event_router_delegate.h @@ -33,23 +33,25 @@ class WebRequestEventRouterDelegate { // Looks up the tab and window ID for a given request. // Called on the IO thread. - virtual void ExtractExtraRequestDetails( - net::URLRequest* request, base::DictionaryValue* out); + virtual void ExtractExtraRequestDetails(const net::URLRequest* request, + base::DictionaryValue* out); // Called to check extra parameters (e.g., tab_id, windown_id) when filtering // event listeners. - virtual bool OnGetMatchingListenersImplCheck( - int tab_id, int window_id, net::URLRequest* request); + virtual bool OnGetMatchingListenersImplCheck(int tab_id, + int window_id, + const net::URLRequest* request); // Logs an extension action. - virtual void LogExtensionActivity( - content::BrowserContext* browser_context, - bool is_incognito, - const std::string& extension_id, - const GURL& url, - const std::string& api_call, - scoped_ptr<base::DictionaryValue> details) {}; - + virtual void LogExtensionActivity(content::BrowserContext* browser_context, + bool is_incognito, + const std::string& extension_id, + const GURL& url, + const std::string& api_call, + scoped_ptr<base::DictionaryValue> details) { + } + + private: DISALLOW_COPY_AND_ASSIGN(WebRequestEventRouterDelegate); }; |