File: offscreen_api.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (283 lines) | stat: -rw-r--r-- 11,058 bytes parent folder | download | duplicates (3)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/offscreen/offscreen_api.h"

#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/strings/stringprintf.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/page_type.h"
#include "extensions/browser/api/offscreen/offscreen_document_manager.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/browser/offscreen_document_host.h"
#include "extensions/common/api/offscreen.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_handlers/incognito_info.h"
#include "extensions/common/switches.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace extensions {

namespace {

// Returns the BrowserContext with which offscreen documents should be
// associated for the given `extension` and `calling_context`. This may be
// different from the `calling_context`, as in the case of spanning mode
// extensions.
content::BrowserContext& GetBrowserContextToUse(
    content::BrowserContext& calling_context,
    const Extension& extension) {
  ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();

  // The on-the-record profile always uses itself.
  if (!calling_context.IsOffTheRecord()) {
    return *client->GetContextForOriginalOnly(&calling_context);
  }

  DCHECK(util::IsIncognitoEnabled(extension.id(), &calling_context))
      << "Only incognito-enabled extensions should have an incognito context";

  // Split-mode extensions use the incognito (calling) context; spanning mode
  // extensions fall back to the original profile.
  bool is_split_mode = IncognitoInfo::IsSplitMode(&extension);
  return is_split_mode
             ? *client->GetContextOwnInstance(&calling_context)
             : *client->GetContextRedirectedToOriginal(&calling_context);
}

// Similar to the above, returns the OffscreenDocumentManager to use for the
// given `extension` and `calling_context`.
OffscreenDocumentManager* GetManagerToUse(
    content::BrowserContext& calling_context,
    const Extension& extension) {
  return OffscreenDocumentManager::Get(
      &GetBrowserContextToUse(calling_context, extension));
}

}  // namespace

OffscreenCreateDocumentFunction::OffscreenCreateDocumentFunction() = default;
OffscreenCreateDocumentFunction::~OffscreenCreateDocumentFunction() = default;

ExtensionFunction::ResponseAction OffscreenCreateDocumentFunction::Run() {
  std::optional<api::offscreen::CreateDocument::Params> params =
      api::offscreen::CreateDocument::Params::Create(args());
  EXTENSION_FUNCTION_VALIDATE(params);
  EXTENSION_FUNCTION_VALIDATE(extension());

  GURL url(params->parameters.url);
  if (!url.is_valid()) {
    url = extension()->ResolveExtensionURL(params->parameters.url);
  }

  if (!url.is_valid() || url::Origin::Create(url) != extension()->origin()) {
    return RespondNow(Error("Invalid URL."));
  }

  OffscreenDocumentManager* manager =
      GetManagerToUse(*browser_context(), *extension());

  if (manager->GetOffscreenDocumentForExtension(*extension())) {
    return RespondNow(
        Error("Only a single offscreen document may be created."));
  }

  const std::vector<api::offscreen::Reason>& reasons =
      params->parameters.reasons;
  std::set<api::offscreen::Reason> deduped_reasons(reasons.begin(),
                                                   reasons.end());
  if (deduped_reasons.empty()) {
    return RespondNow(Error("A `reason` must be provided."));
  }

  if (base::Contains(deduped_reasons, api::offscreen::Reason::kTesting) &&
      !base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kOffscreenDocumentTesting)) {
    return RespondNow(Error(base::StringPrintf(
        "The `TESTING` reason is only available with the --%s "
        "commandline switch applied.",
        switches::kOffscreenDocumentTesting)));
  }

  OffscreenDocumentHost* offscreen_document =
      manager->CreateOffscreenDocument(*extension(), url, deduped_reasons);
  DCHECK(offscreen_document);

  // We assume it's impossible for a document to entirely synchronously load. If
  // that ever changes, we'll need to update this to check the status of the
  // load and respond synchronously.
  DCHECK(!offscreen_document->has_loaded_once());

  host_observer_.Observe(offscreen_document);

  // Add a reference so that we can respond to the extension once the
  // offscreen document finishes its initial load.
  // Balanced in either `OnBrowserContextShutdown()` or
  // `SendResponseToExtension()`.
  AddRef();

  return RespondLater();
}

void OffscreenCreateDocumentFunction::OnBrowserContextShutdown() {
  // Release dangling lifetime pointers and bail. No point in responding now;
  // the context is shutting down. Reset `host_observer_` first to allay any
  // re-entrancy concerns about the host being destructed at this point.
  host_observer_.Reset();
  Release();  // Balanced in Run().
}

void OffscreenCreateDocumentFunction::OnExtensionHostDestroyed(
    ExtensionHost* host) {
  SendResponseToExtension(
      Error("Offscreen document closed before fully loading."));
  // WARNING: `this` can be deleted now!
}

void OffscreenCreateDocumentFunction::OnExtensionHostDidStopFirstLoad(
    const ExtensionHost* host) {
  content::NavigationEntry* nav_entry =
      host->host_contents()->GetController().GetLastCommittedEntry();
  // If the page failed to load, fire an error instead.
  if (!nav_entry || nav_entry->GetPageType() == content::PAGE_TYPE_ERROR) {
    // We need to do this asynchronously by posting a task since this is
    // currently within the context of being notified as an observer that the
    // ExtensionHost finished its first load. `NotifyPageFailedToLoad()` will
    // delete the extension host, which isn't allowed in the middle of observer
    // iteration.
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        base::BindOnce(&OffscreenCreateDocumentFunction::NotifyPageFailedToLoad,
                       this));
    return;
  }

  SendResponseToExtension(NoArguments());
}

void OffscreenCreateDocumentFunction::NotifyPageFailedToLoad() {
  OffscreenDocumentManager* manager =
      GetManagerToUse(*browser_context(), *extension());
  OffscreenDocumentHost* offscreen_document =
      manager->GetOffscreenDocumentForExtension(*extension());
  if (!offscreen_document ||
      !host_observer_.IsObservingSource(offscreen_document)) {
    // It's possible the offscreen document went away in between when we
    // queued up the task to notify the page failed to load and when the
    // task ran (or, rarer yet, that it went away and there's a whole new
    // offscreen document in its place). In that case, the function should
    // have already responded (such as due to the ExtensionHost closing), or
    // it should be an edge case such as the browser shutting down. Bail out.
    // ExtensionFunction's dtor will check that this function properly
    // responded, if it should have.
    return;
  }

  // In any other case, we shouldn't have responded to the extension yet.
  CHECK(!did_respond());

  // The document still exists. Since it failed to load, we should close it and
  // notify the extension.

  // Remove ourselves as an observer, since otherwise closing the document
  // would trigger `OnExtensionHostDestroyed()`.
  host_observer_.Reset();

  // Close out the document and notify the calling extension.
  manager->CloseOffscreenDocumentForExtension(*extension());
  SendResponseToExtension(Error("Page failed to load."));
  return;
}

void OffscreenCreateDocumentFunction::SendResponseToExtension(
    ResponseValue response_value) {
  DCHECK(browser_context())
      << "SendResponseToExtension() should never be called after context "
      << "shutdown";

  // Even though the function is destroyed after responding to the extension,
  // this process happens asynchronously. Stop observing the host now to avoid
  // any chance of being notified of future events.
  host_observer_.Reset();

  Respond(std::move(response_value));
  Release();  // Balanced in Run().
  // WARNING: `this` can be deleted now!
}

OffscreenCloseDocumentFunction::OffscreenCloseDocumentFunction() = default;
OffscreenCloseDocumentFunction::~OffscreenCloseDocumentFunction() = default;

ExtensionFunction::ResponseAction OffscreenCloseDocumentFunction::Run() {
  EXTENSION_FUNCTION_VALIDATE(extension());

  OffscreenDocumentManager* manager =
      GetManagerToUse(*browser_context(), *extension());
  OffscreenDocumentHost* offscreen_document =
      manager->GetOffscreenDocumentForExtension(*extension());
  if (!offscreen_document) {
    return RespondNow(Error("No current offscreen document."));
  }

  host_observer_.Observe(offscreen_document);

  // Add a reference so that we can respond to the extension once the
  // offscreen document finishes closing.
  // Balanced in either `OnBrowserContextShutdown()` or
  // `SendResponseToExtension()`.
  AddRef();
  manager->CloseOffscreenDocumentForExtension(*extension());

  return RespondLater();
}

void OffscreenCloseDocumentFunction::OnBrowserContextShutdown() {
  // Release dangling lifetime pointers and bail. No point in responding now;
  // the context is shutting down. Reset `host_observer_` first to allay any
  // re-entrancy concerns about the host being destructed at this point.
  host_observer_.Reset();
  Release();  // Balanced in Run().
}

void OffscreenCloseDocumentFunction::OnExtensionHostDestroyed(
    ExtensionHost* host) {
  SendResponseToExtension(NoArguments());
  // The host is destroyed, so ensure we're no longer observing it.
  DCHECK(!host_observer_.IsObserving());
}

void OffscreenCloseDocumentFunction::SendResponseToExtension(
    ResponseValue response_value) {
  DCHECK(browser_context())
      << "SendResponseToExtension() should never be called after context "
      << "shutdown";

  // Even though the function is destroyed after responding to the extension,
  // this process happens asynchronously. Stop observing the host now to avoid
  // any chance of being notified of future events.
  host_observer_.Reset();

  Respond(std::move(response_value));
  Release();  // Balanced in Run().
}

OffscreenHasDocumentFunction::OffscreenHasDocumentFunction() = default;
OffscreenHasDocumentFunction::~OffscreenHasDocumentFunction() = default;

ExtensionFunction::ResponseAction OffscreenHasDocumentFunction::Run() {
  EXTENSION_FUNCTION_VALIDATE(extension());

  bool has_document =
      GetManagerToUse(*browser_context(), *extension())
          ->GetOffscreenDocumentForExtension(*extension()) != nullptr;
  return RespondNow(WithArguments(has_document));
}

}  // namespace extensions