blob: 6b4723ac096e13a5ee9a28f86c1c324d5e2d9aaf [file] [log] [blame]
xunjieli413a68782015-06-16 17:15:431// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef EXTENSIONS_BROWSER_EXTENSION_THROTTLE_MANAGER_H_
6#define EXTENSIONS_BROWSER_EXTENSION_THROTTLE_MANAGER_H_
7
8#include <map>
dchengf5d241082016-04-21 03:43:119#include <memory>
xunjieli413a68782015-06-16 17:15:4310#include <string>
11
avic9cec102015-12-23 00:39:2612#include "base/macros.h"
xunjieli413a68782015-06-16 17:15:4313#include "base/memory/ref_counted.h"
gab370841f22017-06-01 14:38:2614#include "base/sequence_checker.h"
xunjieli413a68782015-06-16 17:15:4315#include "base/threading/platform_thread.h"
16#include "extensions/browser/extension_throttle_entry.h"
xunjielie484e2d62015-06-19 14:31:2117#include "net/base/backoff_entry.h"
xunjieli413a68782015-06-16 17:15:4318#include "net/base/net_export.h"
19#include "net/base/network_change_notifier.h"
20#include "url/gurl.h"
21
22namespace content {
23class ResourceThrottle;
24}
25
26namespace net {
xunjieli413a68782015-06-16 17:15:4327class NetLog;
tfarina60a0ae752016-09-24 06:56:1428class NetLogWithSource;
xunjieli413a68782015-06-16 17:15:4329}
30
31namespace extensions {
32
33// Class that registers URL request throttler entries for URLs being accessed
34// in order to supervise traffic. URL requests for HTTP contents should
35// register their URLs in this manager on each request.
36//
37// ExtensionThrottleManager maintains a map of URL IDs to URL request
38// throttler entries. It creates URL request throttler entries when new URLs
39// are registered, and does garbage collection from time to time in order to
40// clean out outdated entries. URL ID consists of lowercased scheme, host, port
41// and path. All URLs converted to the same ID will share the same entry.
42class ExtensionThrottleManager
gab370841f22017-06-01 14:38:2643 : public net::NetworkChangeNotifier::IPAddressObserver,
xunjieli413a68782015-06-16 17:15:4344 public net::NetworkChangeNotifier::ConnectionTypeObserver {
45 public:
46 ExtensionThrottleManager();
47 ~ExtensionThrottleManager() override;
48
49 // Creates a content::ResourceThrottle for |request| to prevent extensions
50 // from requesting a URL too often, if such a throttle is needed.
dchengf5d241082016-04-21 03:43:1151 std::unique_ptr<content::ResourceThrottle> MaybeCreateThrottle(
xunjieli413a68782015-06-16 17:15:4352 const net::URLRequest* request);
53
54 // TODO(xunjieli): Remove this method and replace with
55 // ShouldRejectRequest(request) and UpdateWithResponse(request, status_code),
56 // which will also allow ExtensionThrottleEntry to no longer be reference
57 // counted, and ExtensionThrottleEntryInterface to be removed.
58
59 // Must be called for every request, returns the URL request throttler entry
60 // associated with the URL. The caller must inform this entry of some events.
61 // Please refer to extension_throttle_entry_interface.h for further
62 // informations.
63 scoped_refptr<ExtensionThrottleEntryInterface> RegisterRequestUrl(
64 const GURL& url);
65
dchengf5d241082016-04-21 03:43:1166 void SetBackoffPolicyForTests(
67 std::unique_ptr<net::BackoffEntry::Policy> policy);
xunjielie484e2d62015-06-19 14:31:2168
xunjieli413a68782015-06-16 17:15:4369 // Registers a new entry in this service and overrides the existing entry (if
70 // any) for the URL. The service will hold a reference to the entry.
71 // It is only used by unit tests.
72 void OverrideEntryForTests(const GURL& url, ExtensionThrottleEntry* entry);
73
74 // Explicitly erases an entry.
75 // This is useful to remove those entries which have got infinite lifetime and
76 // thus won't be garbage collected.
77 // It is only used by unit tests.
78 void EraseEntryForTests(const GURL& url);
79
80 // Sets whether to ignore net::LOAD_MAYBE_USER_GESTURE of the request for
81 // testing. Otherwise, requests will not be throttled when they may have been
82 // throttled in response to a recent user gesture, though they're still
83 // counted for the purpose of throttling other requests.
84 void SetIgnoreUserGestureLoadFlagForTests(
85 bool ignore_user_gesture_load_flag_for_tests);
86
87 // Turns threading model verification on or off. Any code that correctly
88 // uses the network stack should preferably call this function to enable
89 // verification of correct adherence to the network stack threading model.
90 void set_enable_thread_checks(bool enable);
91 bool enable_thread_checks() const;
92
93 // Whether throttling is enabled or not.
94 void set_enforce_throttling(bool enforce);
95 bool enforce_throttling();
96
97 // Sets the net::NetLog instance to use.
98 void set_net_log(net::NetLog* net_log);
99 net::NetLog* net_log() const;
100
101 // IPAddressObserver interface.
102 void OnIPAddressChanged() override;
103
104 // ConnectionTypeObserver interface.
105 void OnConnectionTypeChanged(
106 net::NetworkChangeNotifier::ConnectionType type) override;
107
108 // Method that allows us to transform a URL into an ID that can be used in our
109 // map. Resulting IDs will be lowercase and consist of the scheme, host, port
110 // and path (without query string, fragment, etc.).
111 // If the URL is invalid, the invalid spec will be returned, without any
112 // transformation.
113 std::string GetIdFromUrl(const GURL& url) const;
114
115 // Method that ensures the map gets cleaned from time to time. The period at
116 // which garbage collecting happens is adjustable with the
117 // kRequestBetweenCollecting constant.
118 void GarbageCollectEntriesIfNecessary();
119
120 // Method that does the actual work of garbage collecting.
121 void GarbageCollectEntries();
122
123 // When we switch from online to offline or change IP addresses, we
124 // clear all back-off history. This is a precaution in case the change in
125 // online state now lets us communicate without error with servers that
126 // we were previously getting 500 or 503 responses from (perhaps the
127 // responses are from a badly-written proxy that should have returned a
128 // 502 or 504 because it's upstream connection was down or it had no route
129 // to the server).
130 void OnNetworkChange();
131
132 // Used by tests.
133 int GetNumberOfEntriesForTests() const { return url_entries_.size(); }
134
135 private:
136 // From each URL we generate an ID composed of the scheme, host, port and path
137 // that allows us to uniquely map an entry to it.
138 typedef std::map<std::string, scoped_refptr<ExtensionThrottleEntry>>
139 UrlEntryMap;
140
141 // Maximum number of entries that we are willing to collect in our map.
142 static const unsigned int kMaximumNumberOfEntries;
143 // Number of requests that will be made between garbage collection.
144 static const unsigned int kRequestsBetweenCollecting;
145
146 // Map that contains a list of URL ID and their matching
147 // ExtensionThrottleEntry.
148 UrlEntryMap url_entries_;
149
150 // This keeps track of how many requests have been made. Used with
151 // GarbageCollectEntries.
152 unsigned int requests_since_last_gc_;
153
154 // Valid after construction.
155 GURL::Replacements url_id_replacements_;
156
157 // Certain tests do not obey the net component's threading policy, so we
158 // keep track of whether we're being used by tests, and turn off certain
159 // checks.
160 //
161 // TODO(joi): See if we can fix the offending unit tests and remove this
162 // workaround.
163 bool enable_thread_checks_;
164
165 // Initially false, switches to true once we have logged because of back-off
166 // being disabled for localhost.
167 bool logged_for_localhost_disabled_;
168
169 // net::NetLog to use, if configured.
tfarina428341112016-09-22 13:38:20170 net::NetLogWithSource net_log_;
xunjieli413a68782015-06-16 17:15:43171
172 // Valid once we've registered for network notifications.
173 base::PlatformThreadId registered_from_thread_;
174
175 bool ignore_user_gesture_load_flag_for_tests_;
176
xunjielie484e2d62015-06-19 14:31:21177 // This is NULL when it is not set for tests.
dchengf5d241082016-04-21 03:43:11178 std::unique_ptr<net::BackoffEntry::Policy> backoff_policy_for_tests_;
xunjielie484e2d62015-06-19 14:31:21179
gab370841f22017-06-01 14:38:26180 SEQUENCE_CHECKER(sequence_checker_);
181
xunjieli413a68782015-06-16 17:15:43182 DISALLOW_COPY_AND_ASSIGN(ExtensionThrottleManager);
183};
184
185} // namespace extensions
186
187#endif // EXTENSIONS_BROWSER_EXTENSION_THROTTLE_MANAGER_H_