• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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 NET_BASE_NETWORK_DELEGATE_H_
6 #define NET_BASE_NETWORK_DELEGATE_H_
7 
8 #include <stdint.h>
9 
10 #include <set>
11 #include <string>
12 
13 #include "base/functional/callback.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/threading/thread_checker.h"
16 #include "net/base/auth.h"
17 #include "net/base/completion_once_callback.h"
18 #include "net/base/net_export.h"
19 #include "net/cookies/canonical_cookie.h"
20 #include "net/cookies/cookie_inclusion_status.h"
21 #include "net/cookies/cookie_setting_override.h"
22 #include "net/cookies/site_for_cookies.h"
23 #include "net/first_party_sets/first_party_set_metadata.h"
24 #include "net/first_party_sets/first_party_sets_cache_filter.h"
25 #include "net/proxy_resolution/proxy_retry_info.h"
26 #include "third_party/abseil-cpp/absl/types/optional.h"
27 
28 class GURL;
29 
30 namespace url {
31 class Origin;
32 }
33 
34 namespace net {
35 
36 // NOTE: Layering violations!
37 // We decided to accept these violations (depending
38 // on other net/ submodules from net/base/), because otherwise NetworkDelegate
39 // would have to be broken up into too many smaller interfaces targeted to each
40 // submodule. Also, since the lower levels in net/ may callback into higher
41 // levels, we may encounter dangerous casting issues.
42 //
43 // NOTE: It is not okay to add any compile-time dependencies on symbols outside
44 // of net/base here, because we have a net_base library. Forward declarations
45 // are ok.
46 class CookieOptions;
47 class HttpRequestHeaders;
48 class HttpResponseHeaders;
49 class IPEndPoint;
50 class SchemefulSite;
51 class URLRequest;
52 
53 class NET_EXPORT NetworkDelegate {
54  public:
55   virtual ~NetworkDelegate();
56 
57   // Notification interface called by the network stack. Note that these
58   // functions mostly forward to the private virtuals. They also add some sanity
59   // checking on parameters. See the corresponding virtuals for explanations of
60   // the methods and their arguments.
61   int NotifyBeforeURLRequest(URLRequest* request,
62                              CompletionOnceCallback callback,
63                              GURL* new_url);
64   using OnBeforeStartTransactionCallback =
65       base::OnceCallback<void(int, const absl::optional<HttpRequestHeaders>&)>;
66   int NotifyBeforeStartTransaction(URLRequest* request,
67                                    const HttpRequestHeaders& headers,
68                                    OnBeforeStartTransactionCallback callback);
69   int NotifyHeadersReceived(
70       URLRequest* request,
71       CompletionOnceCallback callback,
72       const HttpResponseHeaders* original_response_headers,
73       scoped_refptr<HttpResponseHeaders>* override_response_headers,
74       const IPEndPoint& remote_endpoint,
75       absl::optional<GURL>* preserve_fragment_on_redirect_url);
76   void NotifyBeforeRedirect(URLRequest* request,
77                             const GURL& new_location);
78   void NotifyResponseStarted(URLRequest* request, int net_error);
79   void NotifyCompleted(URLRequest* request, bool started, int net_error);
80   void NotifyURLRequestDestroyed(URLRequest* request);
81   void NotifyPACScriptError(int line_number, const std::u16string& error);
82   bool AnnotateAndMoveUserBlockedCookies(
83       const URLRequest& request,
84       const net::FirstPartySetMetadata& first_party_set_metadata,
85       CookieAccessResultList& maybe_included_cookies,
86       CookieAccessResultList& excluded_cookies);
87   bool CanSetCookie(const URLRequest& request,
88                     const net::CanonicalCookie& cookie,
89                     CookieOptions* options);
90 
91   // PrivacySetting is kStateDisallowed iff the given |url| has to be
92   // requested over connection that is not tracked by the server.
93   //
94   // Usually PrivacySetting is kStateAllowed, unless user privacy settings
95   // block cookies from being get or set.
96   //
97   // It may be set to kPartitionedStateAllowedOnly if the request allows
98   // partitioned state to be sent over the connection, but unpartitioned
99   // state should be blocked.
100   enum class PrivacySetting {
101     kStateAllowed,
102     kStateDisallowed,
103     // First-party requests will never have this setting.
104     kPartitionedStateAllowedOnly,
105   };
106   PrivacySetting ForcePrivacyMode(const URLRequest& request) const;
107 
108   bool CancelURLRequestWithPolicyViolatingReferrerHeader(
109       const URLRequest& request,
110       const GURL& target_url,
111       const GURL& referrer_url) const;
112 
113   bool CanQueueReportingReport(const url::Origin& origin) const;
114   void CanSendReportingReports(
115       std::set<url::Origin> origins,
116       base::OnceCallback<void(std::set<url::Origin>)> result_callback) const;
117   bool CanSetReportingClient(const url::Origin& origin,
118                              const GURL& endpoint) const;
119   bool CanUseReportingClient(const url::Origin& origin,
120                              const GURL& endpoint) const;
121 
122   // Gets the First-Party Sets cache filter info, which is used to mark the
123   // cache and determine if the previously stored cache of `request_site` can be
124   // accessed.
125   //
126   // The result may be returned synchronously, or `callback` may be invoked
127   // asynchronously with the result. The callback will be invoked iff the return
128   // value is nullopt; i.e. a result will be provided via return value or
129   // callback, but not both, and not neither.
130   absl::optional<FirstPartySetsCacheFilter::MatchInfo>
131   GetFirstPartySetsCacheFilterMatchInfoMaybeAsync(
132       const SchemefulSite& request_site,
133       base::OnceCallback<void(FirstPartySetsCacheFilter::MatchInfo)> callback)
134       const;
135 
136  protected:
137   // Adds the given ExclusionReason to all cookies in
138   // `mayble_included_cookies`, and moves the contents of
139   // `maybe_included_cookies` to `excluded_cookies`.
140   static void ExcludeAllCookies(
141       net::CookieInclusionStatus::ExclusionReason reason,
142       net::CookieAccessResultList& maybe_included_cookies,
143       net::CookieAccessResultList& excluded_cookies);
144 
145   // Moves any cookie in `maybe_included_cookies` that has an ExclusionReason
146   // into `excluded_cookies`.
147   static void MoveExcludedCookies(
148       net::CookieAccessResultList& maybe_included_cookies,
149       net::CookieAccessResultList& excluded_cookies);
150 
151   THREAD_CHECKER(thread_checker_);
152 
153  private:
154   FRIEND_TEST_ALL_PREFIXES(NetworkDelegateTest, ExcludeAllCookies);
155   FRIEND_TEST_ALL_PREFIXES(NetworkDelegateTest, MoveExcludedCookies);
156   // This is the interface for subclasses of NetworkDelegate to implement. These
157   // member functions will be called by the respective public notification
158   // member function, which will perform basic sanity checking.
159   //
160   // Note that these member functions refer to URLRequests which may be canceled
161   // or destroyed at any time. Implementations which return ERR_IO_PENDING must
162   // also implement OnURLRequestDestroyed and OnCompleted to handle cancelation.
163   // See below for details.
164   //
165   // (NetworkDelegateImpl has default implementations of these member functions.
166   // NetworkDelegate implementations should consider subclassing
167   // NetworkDelegateImpl.)
168 
169   // Called before a request is sent. Allows the delegate to rewrite the URL
170   // being fetched by modifying |new_url|. If set, the URL must be valid. The
171   // reference fragment from the original URL is not automatically appended to
172   // |new_url|; callers are responsible for copying the reference fragment if
173   // desired.
174   //
175   // Returns OK to continue with the request, ERR_IO_PENDING if the result is
176   // not ready yet, and any other status code to cancel the request.  If
177   // returning ERR_IO_PENDING, call |callback| when the result is ready. Note,
178   // however, that a pending operation may be cancelled by
179   // OnURLRequestDestroyed. Once cancelled, |request| and |new_url| become
180   // invalid and |callback| may not be called.
181   //
182   // The default implementation returns OK (continue with request).
183   virtual int OnBeforeURLRequest(URLRequest* request,
184                                  CompletionOnceCallback callback,
185                                  GURL* new_url) = 0;
186 
187   // Called right before the network transaction starts. Allows the delegate to
188   // read |headers| and modify them by passing a new copy to |callback| before
189   // they get sent out.
190   //
191   // Returns OK to continue with the request, ERR_IO_PENDING if the result is
192   // not ready yet, and any other status code to cancel the request. If
193   // returning ERR_IO_PENDING, call |callback| when the result is ready. Note,
194   // however, that a pending operation may be cancelled by OnURLRequestDestroyed
195   // or OnCompleted. Once cancelled, |request| and |headers| become invalid and
196   // |callback| may not be called.
197   //
198   // The default implementation returns OK (continue with request).
199   virtual int OnBeforeStartTransaction(
200       URLRequest* request,
201       const HttpRequestHeaders& headers,
202       OnBeforeStartTransactionCallback callback) = 0;
203 
204   // Called for HTTP requests when the headers have been received.
205   // |original_response_headers| contains the headers as received over the
206   // network, these must not be modified. |override_response_headers| can be set
207   // to new values, that should be considered as overriding
208   // |original_response_headers|.
209   // If the response is a redirect, and the Location response header value is
210   // identical to |preserve_fragment_on_redirect_url|, then the redirect is
211   // never blocked and the reference fragment is not copied from the original
212   // URL to the redirection target.
213   //
214   // Returns OK to continue with the request, ERR_IO_PENDING if the result is
215   // not ready yet, and any other status code to cancel the request. If
216   // returning ERR_IO_PENDING, call |callback| when the result is ready. Note,
217   // however, that a pending operation may be cancelled by
218   // OnURLRequestDestroyed. Once cancelled, |request|,
219   // |original_response_headers|, |override_response_headers|, and
220   // |preserve_fragment_on_redirect_url| become invalid and |callback| may not
221   // be called.
222   virtual int OnHeadersReceived(
223       URLRequest* request,
224       CompletionOnceCallback callback,
225       const HttpResponseHeaders* original_response_headers,
226       scoped_refptr<HttpResponseHeaders>* override_response_headers,
227       const IPEndPoint& remote_endpoint,
228       absl::optional<GURL>* preserve_fragment_on_redirect_url) = 0;
229 
230   // Called right after a redirect response code was received. |new_location| is
231   // only valid for the duration of the call.
232   virtual void OnBeforeRedirect(URLRequest* request,
233                                 const GURL& new_location) = 0;
234 
235   // This corresponds to URLRequestDelegate::OnResponseStarted.
236   virtual void OnResponseStarted(URLRequest* request, int net_error) = 0;
237 
238   // Indicates that the URL request has been completed or failed.
239   // |started| indicates whether the request has been started. If false,
240   // some information like the socket address is not available.
241   virtual void OnCompleted(URLRequest* request,
242                            bool started,
243                            int net_error) = 0;
244 
245   // Called when an URLRequest is being destroyed. Note that the request is
246   // being deleted, so it's not safe to call any methods that may result in
247   // a virtual method call.
248   virtual void OnURLRequestDestroyed(URLRequest* request) = 0;
249 
250   // Corresponds to ProxyResolverJSBindings::OnError.
251   virtual void OnPACScriptError(int line_number,
252                                 const std::u16string& error) = 0;
253 
254   // Called when reading cookies to allow the network delegate to block access
255   // to individual cookies, by adding the appropriate ExclusionReason and moving
256   // them to the `excluded_cookies` list.  This method will never be invoked
257   // when LOAD_DO_NOT_SEND_COOKIES is specified.
258   //
259   // Returns false if the delegate has blocked access to all cookies; true
260   // otherwise.
261   virtual bool OnAnnotateAndMoveUserBlockedCookies(
262       const URLRequest& request,
263       const net::FirstPartySetMetadata& first_party_set_metadata,
264       net::CookieAccessResultList& maybe_included_cookies,
265       net::CookieAccessResultList& excluded_cookies) = 0;
266 
267   // Called when a cookie is set to allow the network delegate to block access
268   // to the cookie. This method will never be invoked when
269   // LOAD_DO_NOT_SAVE_COOKIES is specified.
270   virtual bool OnCanSetCookie(const URLRequest& request,
271                               const CanonicalCookie& cookie,
272                               CookieOptions* options) = 0;
273 
274   virtual PrivacySetting OnForcePrivacyMode(
275       const URLRequest& request) const = 0;
276 
277   // Called when the |referrer_url| for requesting |target_url| during handling
278   // of the |request| is does not comply with the referrer policy (e.g. a
279   // secure referrer for an insecure initial target).
280   // Returns true if the request should be cancelled. Otherwise, the referrer
281   // header is stripped from the request.
282   virtual bool OnCancelURLRequestWithPolicyViolatingReferrerHeader(
283       const URLRequest& request,
284       const GURL& target_url,
285       const GURL& referrer_url) const = 0;
286 
287   virtual bool OnCanQueueReportingReport(const url::Origin& origin) const = 0;
288 
289   virtual void OnCanSendReportingReports(
290       std::set<url::Origin> origins,
291       base::OnceCallback<void(std::set<url::Origin>)> result_callback)
292       const = 0;
293 
294   virtual bool OnCanSetReportingClient(const url::Origin& origin,
295                                        const GURL& endpoint) const = 0;
296 
297   virtual bool OnCanUseReportingClient(const url::Origin& origin,
298                                        const GURL& endpoint) const = 0;
299 
300   virtual absl::optional<FirstPartySetsCacheFilter::MatchInfo>
301   OnGetFirstPartySetsCacheFilterMatchInfoMaybeAsync(
302       const SchemefulSite& request_site,
303       base::OnceCallback<void(FirstPartySetsCacheFilter::MatchInfo)> callback)
304       const = 0;
305 };
306 
307 }  // namespace net
308 
309 #endif  // NET_BASE_NETWORK_DELEGATE_H_
310