summaryrefslogtreecommitdiffstats
path: root/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.h
blob: a89f9579c574abb84b9b24d59697eaea67487208 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef DocumentLoader_h
#define DocumentLoader_h

#include <memory>
#include "base/memory/scoped_refptr.h"
#include "base/unguessable_token.h"
#include "bindings/core/v8/SourceLocation.h"
#include "core/CoreExport.h"
#include "core/dom/ViewportDescription.h"
#include "core/dom/WeakIdentifierMap.h"
#include "core/frame/FrameTypes.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/html/parser/ParserSynchronizationPolicy.h"
#include "core/loader/DocumentLoadTiming.h"
#include "core/loader/FrameLoaderTypes.h"
#include "core/loader/LinkLoader.h"
#include "core/loader/NavigationPolicy.h"
#include "platform/SharedBuffer.h"
#include "platform/loader/fetch/ClientHintsPreferences.h"
#include "platform/loader/fetch/RawResource.h"
#include "platform/loader/fetch/ResourceError.h"
#include "platform/loader/fetch/ResourceRequest.h"
#include "platform/loader/fetch/ResourceResponse.h"
#include "platform/loader/fetch/SubstituteData.h"
#include "platform/wtf/HashSet.h"
#include "public/platform/WebLoadingBehaviorFlag.h"
#include "public/web/WebGlobalObjectReusePolicy.h"

#include <memory>

namespace blink {

class ApplicationCacheHost;
class CSSPreloaderResourceClient;
class Document;
class DocumentParser;
class FrameLoader;
class HistoryItem;
class LocalFrame;
class LocalFrameClient;
class ResourceFetcher;
class ResourceTimingInfo;
class SerializedScriptValue;
class SubresourceFilter;
class WebServiceWorkerNetworkProvider;
struct ViewportDescriptionWrapper;

// The DocumentLoader fetches a main resource and handles the result.
class CORE_EXPORT DocumentLoader
    : public GarbageCollectedFinalized<DocumentLoader>,
      private RawResourceClient {
  USING_GARBAGE_COLLECTED_MIXIN(DocumentLoader);

 public:
  static DocumentLoader* Create(
      LocalFrame* frame,
      const ResourceRequest& request,
      const SubstituteData& data,
      ClientRedirectPolicy client_redirect_policy,
      const base::UnguessableToken& devtools_navigation_token) {
    DCHECK(frame);

    return new DocumentLoader(frame, request, data, client_redirect_policy,
                              devtools_navigation_token);
  }
  ~DocumentLoader() override;

  LocalFrame* GetFrame() const { return frame_; }

  ResourceTimingInfo* GetNavigationTimingInfo() const;

  virtual void DetachFromFrame();

  unsigned long MainResourceIdentifier() const;

  void ReplaceDocumentWhileExecutingJavaScriptURL(const KURL&,
                                                  Document* owner_document,
                                                  WebGlobalObjectReusePolicy,
                                                  const String& source);

  const AtomicString& MimeType() const;

  const ResourceRequest& OriginalRequest() const;

  const ResourceRequest& GetRequest() const;

  ResourceFetcher* Fetcher() const { return fetcher_.Get(); }

  void SetSubresourceFilter(SubresourceFilter*);
  SubresourceFilter* GetSubresourceFilter() const {
    return subresource_filter_.Get();
  }

  const SubstituteData& GetSubstituteData() const { return substitute_data_; }

  const KURL& Url() const;
  const KURL& UnreachableURL() const;
  const KURL& UrlForHistory() const;

  void DidChangePerformanceTiming();
  void DidObserveLoadingBehavior(WebLoadingBehaviorFlag);
  void UpdateForSameDocumentNavigation(const KURL&,
                                       SameDocumentNavigationSource,
                                       scoped_refptr<SerializedScriptValue>,
                                       HistoryScrollRestorationType,
                                       FrameLoadType,
                                       Document*);
  const ResourceResponse& GetResponse() const { return response_; }
  bool IsClientRedirect() const { return is_client_redirect_; }
  void SetIsClientRedirect(bool is_client_redirect) {
    is_client_redirect_ = is_client_redirect;
  }
  bool ReplacesCurrentHistoryItem() const {
    return replaces_current_history_item_;
  }
  void SetReplacesCurrentHistoryItem(bool replaces_current_history_item) {
    replaces_current_history_item_ = replaces_current_history_item;
  }

  bool IsCommittedButEmpty() const {
    return state_ >= kCommitted && !data_received_;
  }

  // Without PlzNavigate, this is only false for a narrow window during
  // navigation start. For PlzNavigate, a navigation sent to the browser will
  // leave a dummy DocumentLoader in the NotStarted state until the navigation
  // is actually handled in the renderer.
  bool DidStart() const { return state_ != kNotStarted; }

  void MarkAsCommitted();
  void SetSentDidFinishLoad() { state_ = kSentDidFinishLoad; }
  bool SentDidFinishLoad() const { return state_ == kSentDidFinishLoad; }

  FrameLoadType LoadType() const { return load_type_; }
  void SetLoadType(FrameLoadType load_type) { load_type_ = load_type; }

  NavigationType GetNavigationType() const { return navigation_type_; }
  void SetNavigationType(NavigationType navigation_type) {
    navigation_type_ = navigation_type;
  }

  void SetItemForHistoryNavigation(HistoryItem* item) { history_item_ = item; }
  HistoryItem* GetHistoryItem() const { return history_item_; }

  void StartLoading();

  DocumentLoadTiming& GetTiming() { return document_load_timing_; }
  const DocumentLoadTiming& GetTiming() const { return document_load_timing_; }

  ApplicationCacheHost* GetApplicationCacheHost() const {
    return application_cache_host_.Get();
  }

  void ClearRedirectChain();
  void AppendRedirect(const KURL&);

  ClientHintsPreferences& GetClientHintsPreferences() {
    return client_hints_preferences_;
  }

  struct InitialScrollState {
    DISALLOW_NEW();
    InitialScrollState()
        : was_scrolled_by_user(false), did_restore_from_history(false) {}

    bool was_scrolled_by_user;
    bool did_restore_from_history;
  };
  InitialScrollState& GetInitialScrollState() { return initial_scroll_state_; }

  void SetWasBlockedAfterCSP() { was_blocked_after_csp_ = true; }
  bool WasBlockedAfterCSP() { return was_blocked_after_csp_; }

  void DispatchLinkHeaderPreloads(ViewportDescriptionWrapper*,
                                  LinkLoader::MediaPreloadPolicy);

  Resource* StartPreload(Resource::Type,
                         FetchParameters&,
                         CSSPreloaderResourceClient*);

  void SetServiceWorkerNetworkProvider(
      std::unique_ptr<WebServiceWorkerNetworkProvider>);

  // May return null before the first HTML tag is inserted by the
  // parser (before didCreateDataSource is called), after the document
  // is detached from frame, or in tests.
  WebServiceWorkerNetworkProvider* GetServiceWorkerNetworkProvider() {
    return service_worker_network_provider_.get();
  }

  std::unique_ptr<SourceLocation> CopySourceLocation() const;
  void SetSourceLocation(std::unique_ptr<SourceLocation>);

  void LoadFailed(const ResourceError&);

  void SetUserActivated();

  void Trace(blink::Visitor*) override;

  // For automation driver-initiated navigations over the devtools protocol,
  // |devtools_navigation_token_| is used to tag the navigation. This navigation
  // token is then sent into the renderer and lands on the DocumentLoader. That
  // way subsequent Blink-level frame lifecycle events can be associated with
  // the concrete navigation.
  // - The value should not be sent back to the browser.
  // - The value on DocumentLoader may be generated in the renderer in some
  // cases, and thus shouldn't be trusted.
  // TODO(crbug.com/783506): Replace devtools navigation token with the generic
  // navigation token that can be passed from renderer to the browser.
  const base::UnguessableToken& GetDevToolsNavigationToken() {
    return devtools_navigation_token_;
  }

  // Returns the currently stored content security policy, if this is called
  // after the document has been installed it will return nullptr as the
  // CSP belongs to the document at that point.
  const ContentSecurityPolicy* GetContentSecurityPolicy() const {
    return content_security_policy_.Get();
  }

 protected:
  DocumentLoader(LocalFrame*,
                 const ResourceRequest&,
                 const SubstituteData&,
                 ClientRedirectPolicy,
                 const base::UnguessableToken& devtools_navigation_token);

  static bool ShouldClearWindowName(
      const LocalFrame&,
      const SecurityOrigin* previous_security_origin,
      const Document& new_document);

  Vector<KURL> redirect_chain_;

 private:
  // installNewDocument() does the work of creating a Document and
  // DocumentParser, as well as creating a new LocalDOMWindow if needed. It also
  // initalizes a bunch of state on the Document (e.g., the state based on
  // response headers).
  enum class InstallNewDocumentReason { kNavigation, kJavascriptURL };
  void InstallNewDocument(const KURL&,
                          Document* owner_document,
                          WebGlobalObjectReusePolicy,
                          const AtomicString& mime_type,
                          const AtomicString& encoding,
                          InstallNewDocumentReason,
                          ParserSynchronizationPolicy,
                          const KURL& overriding_url);
  void DidInstallNewDocument(Document*);
  void WillCommitNavigation();
  void DidCommitNavigation(WebGlobalObjectReusePolicy);

  void CommitNavigation(const AtomicString& mime_type,
                        const KURL& overriding_url = KURL());

  // Use these method only where it's guaranteed that |m_frame| hasn't been
  // cleared.
  FrameLoader& GetFrameLoader() const;
  LocalFrameClient& GetLocalFrameClient() const;

  void CommitData(const char* bytes, size_t length);

  bool MaybeCreateArchive();

  void FinishedLoading(double finish_time);
  void CancelLoadAfterCSPDenied(const ResourceResponse&);

  enum class HistoryNavigationType {
    kDifferentDocument,
    kFragment,
    kHistoryApi
  };
  void SetHistoryItemStateForCommit(HistoryItem* old_item,
                                    FrameLoadType,
                                    HistoryNavigationType);

  // RawResourceClient implementation
  bool RedirectReceived(Resource*,
                        const ResourceRequest&,
                        const ResourceResponse&) final;
  void ResponseReceived(Resource*,
                        const ResourceResponse&,
                        std::unique_ptr<WebDataConsumerHandle>) final;
  void DataReceived(Resource*, const char* data, size_t length) final;

  // ResourceClient implementation
  void NotifyFinished(Resource*) final;
  String DebugName() const override { return "DocumentLoader"; }

  void ProcessData(const char* data, size_t length);

  bool MaybeLoadEmpty();

  bool IsRedirectAfterPost(const ResourceRequest&, const ResourceResponse&);

  bool ShouldContinueForResponse() const;

  Member<LocalFrame> frame_;
  Member<ResourceFetcher> fetcher_;

  Member<HistoryItem> history_item_;

  // The parser that was created when the current Document was installed.
  // document.open() may create a new parser at a later point, but this
  // will not be updated.
  Member<DocumentParser> parser_;

  Member<SubresourceFilter> subresource_filter_;

  // A reference to actual request used to create the data source.
  // The only part of this request that should change is the url, and
  // that only in the case of a same-document navigation.
  ResourceRequest original_request_;

  SubstituteData substitute_data_;

  // The 'working' request. It may be mutated
  // several times from the original request to include additional
  // headers, cookie information, canonicalization and redirects.
  ResourceRequest request_;

  ResourceResponse response_;

  FrameLoadType load_type_;

  bool is_client_redirect_;
  bool replaces_current_history_item_;
  bool data_received_;

  NavigationType navigation_type_;

  DocumentLoadTiming document_load_timing_;

  double time_of_last_data_received_;

  Member<ApplicationCacheHost> application_cache_host_;

  std::unique_ptr<WebServiceWorkerNetworkProvider>
      service_worker_network_provider_;

  Member<ContentSecurityPolicy> content_security_policy_;
  ClientHintsPreferences client_hints_preferences_;
  InitialScrollState initial_scroll_state_;

  bool was_blocked_after_csp_;

  // PlzNavigate: set when committing a navigation. The data has originally been
  // captured when the navigation was sent to the browser process, and it is
  // sent back at commit time.
  std::unique_ptr<SourceLocation> source_location_;

  enum State { kNotStarted, kProvisional, kCommitted, kSentDidFinishLoad };
  State state_;

  // Used to protect against reentrancy into dataReceived().
  bool in_data_received_;
  scoped_refptr<SharedBuffer> data_buffer_;
  base::UnguessableToken devtools_navigation_token_;

  // Whether this load request comes from a user activation.
  bool user_activated_;
};

DECLARE_WEAK_IDENTIFIER_MAP(DocumentLoader);

}  // namespace blink

#endif  // DocumentLoader_h