summaryrefslogtreecommitdiffstats
path: root/src/core/extensions/extension_system_qt.cpp
blob: 99abc497ae6607a796a20e89336783a47b4b8104 (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
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extension_system_qt.h"

#include <algorithm>

#include "base/base_paths.h"
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "chrome/common/buildflags.h"
#include "components/crx_file/id_util.h"
#include "components/value_store/value_store_factory.h"
#include "components/value_store/value_store_factory_impl.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/common/webplugininfo.h"
#include "extensions/browser/content_verifier.h"
#include "extensions/browser/content_verifier_delegate.h"
#include "extensions/browser/extension_pref_store.h"
#include "extensions/browser/extension_pref_value_map.h"
#include "extensions/browser/extension_pref_value_map_factory.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/info_map.h"
#include "extensions/browser/notification_types.h"
#include "extensions/browser/null_app_sorting.h"
#include "extensions/browser/quota_service.h"
#include "extensions/browser/renderer_startup_helper.h"
#include "extensions/browser/service_worker_manager.h"
#include "extensions/browser/user_script_manager.h"
#include "extensions/common/constants.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/mime_types_handler.h"
#include "extensions/common/manifest_url_handlers.h"
#include "net/base/mime_util.h"
#include "qtwebengine/grit/qt_webengine_resources.h"
#include "ui/base/resource/resource_bundle.h"

using content::BrowserThread;

namespace extensions {

namespace {

std::string GenerateId(const base::DictionaryValue *manifest, const base::FilePath &path)
{
    std::string raw_key;
    std::string id_input;
    CHECK(manifest->GetString(manifest_keys::kPublicKey, &raw_key));
    CHECK(Extension::ParsePEMKeyBytes(raw_key, &id_input));
    std::string id = crx_file::id_util::GenerateId(id_input);
    return id;
}

// Implementation based on ComponentLoader::ParseManifest.
std::unique_ptr<base::DictionaryValue> ParseManifest(const std::string &manifest_contents)
{
    JSONStringValueDeserializer deserializer(manifest_contents);
    std::unique_ptr<base::Value> manifest(deserializer.Deserialize(NULL, NULL));

    if (!manifest.get() || !manifest->is_dict()) {
        LOG(ERROR) << "Failed to parse extension manifest.";
        return NULL;
    }
    // Transfer ownership to the caller.
    return base::DictionaryValue::From(std::move(manifest));
}

} // namespace

// Dummy Content Verifier Delegate. Added to prevent crashes.
class ContentVerifierDelegateQt : public ContentVerifierDelegate
{
public:
    ~ContentVerifierDelegateQt() override {}

    // This should return what verification mode is appropriate for the given
    // extension, if any.
    VerifierSourceType GetVerifierSourceType(const Extension &extension) override
    { return VerifierSourceType::NONE; }

    // Should return the public key to use for validating signatures via the two
    // out parameters.
    ContentVerifierKey GetPublicKey() override { return ContentVerifierKey(); }
    // This should return a URL that can be used to fetch the
    // verified_contents.json containing signatures for the given extension
    // id/version pair.
    GURL GetSignatureFetchUrl(const std::string &extension_id, const base::Version &version) override { return GURL(); }

    // This should return the set of file paths for images used within the
    // browser process. (These may get transcoded during the install process).
    std::set<base::FilePath> GetBrowserImagePaths(const extensions::Extension *extension) override
    {
        return std::set<base::FilePath>();
    }

    // Called when the content verifier detects that a read of a file inside
    // an extension did not match its expected hash.
    void VerifyFailed(const std::string &extension_id, ContentVerifyJob::FailureReason reason) override {}

    // Called when ExtensionSystem is shutting down.
    void Shutdown() override {}
};

void ExtensionSystemQt::LoadExtension(std::string extension_id, std::unique_ptr<base::DictionaryValue> manifest, const base::FilePath &directory)
{
    int flags = Extension::REQUIRE_KEY;
    std::string error;
    scoped_refptr<const Extension> extension = Extension::Create(
            directory,
            mojom::ManifestLocation::kComponent,
            *manifest,
            flags,
            &error);
    if (!extension.get())
        LOG(ERROR) << error;

    base::PostTask(FROM_HERE, {content::BrowserThread::IO},
            base::BindOnce(&InfoMap::AddExtension,
                           base::Unretained(info_map()),
                           base::RetainedRef(extension),
                           base::Time::Now(),
                           true,
                           false));
    extension_registry_->AddEnabled(extension.get());

    NotifyExtensionLoaded(extension.get());
}

void ExtensionSystemQt::OnExtensionRegisteredWithRequestContexts(scoped_refptr<const extensions::Extension> extension)
{
    extension_registry_->AddReady(extension);
    if (extension_registry_->enabled_extensions().Contains(extension->id()))
        extension_registry_->TriggerOnReady(extension.get());
}

// Implementation based on ExtensionService::NotifyExtensionLoaded.
void ExtensionSystemQt::NotifyExtensionLoaded(const Extension *extension)
{
    // The URLRequestContexts need to be first to know that the extension
    // was loaded, otherwise a race can arise where a renderer that is created
    // for the extension may try to load an extension URL with an extension id
    // that the request context doesn't yet know about. The profile is responsible
    // for ensuring its URLRequestContexts appropriately discover the loaded
    // extension.
    RegisterExtensionWithRequestContexts(
            extension,
            base::BindRepeating(&ExtensionSystemQt::OnExtensionRegisteredWithRequestContexts,
                                weak_ptr_factory_.GetWeakPtr(),
                                base::WrapRefCounted(extension)));

    // Tell renderers about the loaded extension.
    renderer_helper_->OnExtensionLoaded(*extension);

    // Tell subsystems that use the ExtensionRegistryObserver::OnExtensionLoaded
    // about the new extension.
    //
    // NOTE: It is important that this happen after notifying the renderers about
    // the new extensions so that if we navigate to an extension URL in
    // ExtensionRegistryObserver::OnExtensionLoaded the renderer is guaranteed to
    // know about it.
    extension_registry_->TriggerOnLoaded(extension);

    // Register plugins included with the extension.
    // Implementation based on PluginManager::OnExtensionLoaded.
    const MimeTypesHandler *handler = MimeTypesHandler::GetHandler(extension);
    if (handler && handler->HasPlugin()) {
        content::WebPluginInfo info;
        info.type = content::WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN;
        info.name = base::UTF8ToUTF16(extension->name());
        info.path = handler->GetPluginPath();
        info.background_color = handler->GetBackgroundColor();
        for (std::set<std::string>::const_iterator mime_type = handler->mime_type_set().begin();
             mime_type != handler->mime_type_set().end(); ++mime_type) {
            content::WebPluginMimeType mime_type_info;
            mime_type_info.mime_type = *mime_type;
            base::FilePath::StringType file_extension;
            if (net::GetPreferredExtensionForMimeType(*mime_type, &file_extension)) {
                mime_type_info.file_extensions.push_back(
                        base::FilePath(file_extension).AsUTF8Unsafe());
            }
            info.mime_types.push_back(mime_type_info);
        }
        content::PluginService *plugin_service =
                content::PluginService::GetInstance();
        plugin_service->RefreshPlugins();
        plugin_service->RegisterInternalPlugin(info, true);
    }
}

bool ExtensionSystemQt::FinishDelayedInstallationIfReady(const std::string &extension_id, bool install_immediately)
{
    // TODO mibrunin
    return false;
}

void ExtensionSystemQt::Shutdown()
{
    if (content_verifier_.get())
        content_verifier_->Shutdown();
}

ServiceWorkerManager *ExtensionSystemQt::service_worker_manager()
{
    return service_worker_manager_.get();
}

ExtensionService *ExtensionSystemQt::extension_service()
{
    return nullptr;
}

ManagementPolicy *ExtensionSystemQt::management_policy()
{
    return nullptr;
}

UserScriptManager *ExtensionSystemQt::user_script_manager()
{
    return user_script_manager_.get();
}

StateStore *ExtensionSystemQt::state_store()
{
    return nullptr;
}

StateStore *ExtensionSystemQt::rules_store()
{
    return nullptr;
}

StateStore *ExtensionSystemQt::dynamic_user_scripts_store()
{
    return nullptr;
}

scoped_refptr<value_store::ValueStoreFactory> ExtensionSystemQt::store_factory()
{
    return store_factory_;
}

InfoMap *ExtensionSystemQt::info_map()
{
    if (!info_map_.get())
        info_map_ = new InfoMap;
    return info_map_.get();
}

QuotaService *ExtensionSystemQt::quota_service()
{
    return quota_service_.get();
}

AppSorting *ExtensionSystemQt::app_sorting()
{
    return app_sorting_.get();
}

ContentVerifier *ExtensionSystemQt::content_verifier()
{
    if (!content_verifier_.get()) {
        content_verifier_ = new ContentVerifier(browser_context_, std::make_unique<ContentVerifierDelegateQt>());
    }
    return content_verifier_.get();
}

ExtensionSystemQt::ExtensionSystemQt(content::BrowserContext *browserContext)
    : browser_context_(browserContext)
    , store_factory_(new value_store::ValueStoreFactoryImpl(browserContext->GetPath()))
    , extension_registry_(ExtensionRegistry::Get(browserContext))
    , renderer_helper_(extensions::RendererStartupHelperFactory::GetForBrowserContext(browserContext))
    , initialized_(false)
    , weak_ptr_factory_(this)
{
}

ExtensionSystemQt::~ExtensionSystemQt()
{
}

void ExtensionSystemQt::Init(bool extensions_enabled)
{
    if (initialized_)
        return;

    initialized_ = true;

    service_worker_manager_ = std::make_unique<ServiceWorkerManager>(browser_context_);
    user_script_manager_ = std::make_unique<UserScriptManager>(browser_context_);
    quota_service_ = std::make_unique<QuotaService>();
    app_sorting_ = std::make_unique<NullAppSorting>();

    // Make the chrome://extension-icon/ resource available.
    // content::URLDataSource::Add(browser_context_, new ExtensionIconSource(browser_context_));

    if (extensions_enabled) {
        // Inform the rest of the extensions system to start.
        ready_.Signal();

        {
            std::string pdf_manifest = ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_PDF_MANIFEST);
            base::ReplaceFirstSubstringAfterOffset(&pdf_manifest, 0, "<NAME>", "chromium-pdf");

            std::unique_ptr<base::DictionaryValue> pdfManifestDict = ParseManifest(pdf_manifest);
            base::FilePath path;
            base::PathService::Get(base::DIR_QT_LIBRARY_DATA, &path);
            path = path.Append(base::FilePath(FILE_PATH_LITERAL("pdf")));
            std::string id = GenerateId(pdfManifestDict.get(), path);
            LoadExtension(id, std::move(pdfManifestDict), path);
        }

#if BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION)
        {
            std::string hangout_manifest = ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(IDR_HANGOUT_SERVICES_MANIFEST);
            std::unique_ptr<base::DictionaryValue> hangoutManifestDict = ParseManifest(hangout_manifest);
            base::FilePath path;
            base::PathService::Get(base::DIR_QT_LIBRARY_DATA, &path);
            path = path.Append(base::FilePath(FILE_PATH_LITERAL("hangout_services")));
            std::string id = GenerateId(hangoutManifestDict.get(), path);
            LoadExtension(id, std::move(hangoutManifestDict), path);
        }
#endif // BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION)
    }
}

void ExtensionSystemQt::InitForRegularProfile(bool extensions_enabled)
{
    if (initialized_)
        return; // Already initialized.
    // The InfoMap needs to be created before the ProcessManager.
    info_map();

    Init(extensions_enabled);
}

std::unique_ptr<ExtensionSet> ExtensionSystemQt::GetDependentExtensions(const Extension *extension)
{
    return base::WrapUnique(new ExtensionSet());
}

void ExtensionSystemQt::RegisterExtensionWithRequestContexts(const Extension *extension,
                                                             base::OnceClosure callback)
{
    base::Time install_time = base::Time::Now();

    bool incognito_enabled = false;
    bool notifications_disabled = false;

    base::PostTaskAndReply(
            FROM_HERE, {BrowserThread::IO},
            base::BindOnce(&InfoMap::AddExtension, info_map(),
                           base::RetainedRef(extension), install_time, incognito_enabled,
                           notifications_disabled),
            std::move(callback));
}

void ExtensionSystemQt::UnregisterExtensionWithRequestContexts(const std::string &extension_id,
                                                               const UnloadedExtensionReason reason)
{
    base::PostTask(
        FROM_HERE, {BrowserThread::IO},
        base::BindOnce(&InfoMap::RemoveExtension, info_map(), extension_id, reason));
}

bool ExtensionSystemQt::is_ready() const
{
    return ready_.is_signaled();
}

} // namespace extensions