summaryrefslogtreecommitdiffstats
path: root/mojo/shell/application_manager.cc
blob: 8588afcaefaf17c01fa1bbfc12134704fa3f10d8 (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
398
399
400
401
402
403
// 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 "mojo/shell/application_manager.h"

#include <stdint.h>

#include <utility>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/process/process.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/trace_event/trace_event.h"
#include "mojo/common/url_type_converters.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/services/package_manager/loader.h"
#include "mojo/shell/application_instance.h"
#include "mojo/shell/connect_util.h"
#include "mojo/shell/public/cpp/connect.h"
#include "mojo/shell/public/cpp/shell_connection.h"
#include "mojo/shell/switches.h"
#include "mojo/util/filename_util.h"

namespace mojo {
namespace shell {

namespace {

void OnEmptyOnConnectCallback(uint32_t remote_id) {}

class ShellApplicationLoader : public ApplicationLoader {
 public:
  explicit ShellApplicationLoader(ApplicationManager* manager)
      : manager_(manager) {}
  ~ShellApplicationLoader() override {}

 private:
  // Overridden from ApplicationLoader:
  void Load(const GURL& url, mojom::ShellClientRequest request) override {
    DCHECK(request.is_pending());
    shell_connection_.reset(new ShellConnection(manager_, std::move(request)));
  }

  ApplicationManager* manager_;
  scoped_ptr<ShellConnection> shell_connection_;

  DISALLOW_COPY_AND_ASSIGN(ShellApplicationLoader);
};

}  // namespace

mojom::Shell::ConnectToApplicationCallback EmptyConnectCallback() {
  return base::Bind(&OnEmptyOnConnectCallback);
}

// static
ApplicationManager::TestAPI::TestAPI(ApplicationManager* manager)
    : manager_(manager) {
}

ApplicationManager::TestAPI::~TestAPI() {
}

bool ApplicationManager::TestAPI::HasRunningInstanceForURL(
    const GURL& url) const {
  return manager_->identity_to_instance_.find(Identity(url)) !=
         manager_->identity_to_instance_.end();
}

////////////////////////////////////////////////////////////////////////////////
// ApplicationManager, public:

ApplicationManager::ApplicationManager(
    bool register_mojo_url_schemes)
    : ApplicationManager(nullptr, nullptr, register_mojo_url_schemes) {}

ApplicationManager::ApplicationManager(
    scoped_ptr<NativeRunnerFactory> native_runner_factory,
    base::TaskRunner* task_runner,
    bool register_mojo_url_schemes)
    : task_runner_(task_runner),
      native_runner_factory_(std::move(native_runner_factory)),
      weak_ptr_factory_(this) {
  SetLoaderForURL(make_scoped_ptr(new ShellApplicationLoader(this)),
                  GURL("mojo://shell/"));

  InitPackageManager(register_mojo_url_schemes);
}

ApplicationManager::~ApplicationManager() {
  TerminateShellConnections();
  STLDeleteValues(&url_to_loader_);
  for (auto& runner : native_runners_)
    runner.reset();
}

void ApplicationManager::ConnectToApplication(
    scoped_ptr<ConnectToApplicationParams> params) {
  TRACE_EVENT_INSTANT1("mojo_shell", "ApplicationManager::ConnectToApplication",
                       TRACE_EVENT_SCOPE_THREAD, "original_url",
                       params->target().url().spec());
  DCHECK(params->target().url().is_valid());

  // Connect to an existing matching instance, if possible.
  if (ConnectToRunningApplication(&params))
    return;

  std::string url = params->target().url().spec();
  shell_resolver_->ResolveMojoURL(
      url,
      base::Bind(&ApplicationManager::OnGotResolvedURL,
                  weak_ptr_factory_.GetWeakPtr(), base::Passed(&params)));
}

void ApplicationManager::SetLoaderForURL(scoped_ptr<ApplicationLoader> loader,
                                         const GURL& url) {
  URLToLoaderMap::iterator it = url_to_loader_.find(url);
  if (it != url_to_loader_.end())
    delete it->second;
  url_to_loader_[url] = loader.release();
}

void ApplicationManager::TerminateShellConnections() {
  STLDeleteValues(&identity_to_instance_);
}

void ApplicationManager::OnApplicationInstanceError(
    ApplicationInstance* instance) {
  // Called from ~ApplicationInstance, so we do not need to call Destroy here.
  const Identity identity = instance->identity();
  base::Closure on_application_end = instance->on_application_end();
  // Remove the shell.
  auto it = identity_to_instance_.find(identity);
  DCHECK(it != identity_to_instance_.end());
  int id = instance->id();
  delete it->second;
  identity_to_instance_.erase(it);
  listeners_.ForAllPtrs(
      [this, id](mojom::ApplicationManagerListener* listener) {
        listener->ApplicationInstanceDestroyed(id);
      });
  if (!on_application_end.is_null())
    on_application_end.Run();
}

ApplicationInstance* ApplicationManager::GetApplicationInstance(
    const Identity& identity) const {
  const auto& it = identity_to_instance_.find(identity);
  return it != identity_to_instance_.end() ? it->second : nullptr;
}

void ApplicationManager::ApplicationPIDAvailable(
    uint32_t id,
    base::ProcessId pid) {
  for (auto& instance : identity_to_instance_) {
    if (instance.second->id() == id) {
      instance.second->set_pid(pid);
      break;
    }
  }
  listeners_.ForAllPtrs(
      [this, id, pid](mojom::ApplicationManagerListener* listener) {
        listener->ApplicationPIDAvailable(id, pid);
      });
}

////////////////////////////////////////////////////////////////////////////////
// ApplicationManager, ShellClient implementation:

bool ApplicationManager::AcceptConnection(Connection* connection) {
  connection->AddInterface<mojom::ApplicationManager>(this);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// ApplicationManager, InterfaceFactory<mojom::ApplicationManager>
//     implementation:

void ApplicationManager::Create(
    Connection* connection,
    mojom::ApplicationManagerRequest request) {
  bindings_.AddBinding(this, std::move(request));
}

////////////////////////////////////////////////////////////////////////////////
// ApplicationManager, mojom::ApplicationManager implemetation:

void ApplicationManager::CreateInstanceForHandle(
    ScopedHandle channel,
    const String& url,
    mojom::CapabilityFilterPtr filter,
    mojom::PIDReceiverRequest pid_receiver) {
  // We don't call ConnectToClient() here since the instance was created
  // manually by other code, not in response to a Connect() request. The newly
  // created instance is identified by |url| and may be subsequently reached by
  // client code using this identity.
  CapabilityFilter local_filter = filter->filter.To<CapabilityFilter>();
  Identity target_id(url.To<GURL>(), std::string(), local_filter);
  mojom::ShellClientRequest request;
  // TODO(beng): do better than url.spec() for application name.
  ApplicationInstance* instance =
      CreateInstance(target_id, base::Closure(), url, &request);
  instance->BindPIDReceiver(std::move(pid_receiver));
  scoped_ptr<NativeRunner> runner =
      native_runner_factory_->Create(base::FilePath());
  runner->InitHost(std::move(channel), std::move(request));
  instance->SetNativeRunner(runner.get());
  native_runners_.push_back(std::move(runner));
}

void ApplicationManager::AddListener(
    mojom::ApplicationManagerListenerPtr listener) {
  Array<mojom::ApplicationInfoPtr> applications;
  for (auto& entry : identity_to_instance_)
    applications.push_back(CreateApplicationInfoForInstance(entry.second));
  listener->SetRunningApplications(std::move(applications));

  listeners_.AddInterfacePtr(std::move(listener));
}

////////////////////////////////////////////////////////////////////////////////
// ApplicationManager, private:

void ApplicationManager::InitPackageManager(bool register_mojo_url_schemes) {
  scoped_ptr<ApplicationLoader> loader(
      new package_manager::Loader(task_runner_, register_mojo_url_schemes));

  mojom::ShellClientRequest request;
  GURL url("mojo://package_manager/");
  CreateInstance(Identity(url), base::Closure(), url.spec(), &request);
  loader->Load(url, std::move(request));

  SetLoaderForURL(std::move(loader), url);

  ConnectToInterface(this, CreateShellIdentity(), url, &shell_resolver_);
}

bool ApplicationManager::ConnectToRunningApplication(
    scoped_ptr<ConnectToApplicationParams>* params) {
  ApplicationInstance* instance = GetApplicationInstance((*params)->target());
  if (!instance)
    return false;

  // TODO(beng): CHECK() that the target URL is already in the application
  //             catalog.
  instance->ConnectToClient(std::move(*params));
  return true;
}

ApplicationInstance* ApplicationManager::CreateInstance(
    const Identity& target_id,
    const base::Closure& on_application_end,
    const String& application_name,
    mojom::ShellClientRequest* request) {
  mojom::ShellClientPtr shell_client;
  *request = GetProxy(&shell_client);
  ApplicationInstance* instance = new ApplicationInstance(
      std::move(shell_client), this, target_id, on_application_end,
      application_name);
  DCHECK(identity_to_instance_.find(target_id) ==
         identity_to_instance_.end());
  identity_to_instance_[target_id] = instance;
  mojom::ApplicationInfoPtr application_info =
      CreateApplicationInfoForInstance(instance);
  listeners_.ForAllPtrs(
      [this, &application_info](mojom::ApplicationManagerListener* listener) {
        listener->ApplicationInstanceCreated(application_info.Clone());
      });
  instance->InitializeApplication();
  return instance;
}

void ApplicationManager::CreateShellClient(
    const Identity& source,
    const Identity& shell_client_factory,
    const GURL& url,
    mojom::ShellClientRequest request) {
  mojom::ShellClientFactory* factory =
      GetShellClientFactory(shell_client_factory, source);
  factory->CreateShellClient(std::move(request), url.spec());
}

mojom::ShellClientFactory* ApplicationManager::GetShellClientFactory(
    const Identity& shell_client_factory_identity,
    const Identity& source_identity) {
  auto it = shell_client_factories_.find(shell_client_factory_identity);
  if (it != shell_client_factories_.end())
    return it->second.get();

  mojom::ShellClientFactoryPtr factory;
  // TODO(beng): we should forward the original source identity!
  ConnectToInterface(this, source_identity, shell_client_factory_identity.url(),
                     &factory);
  mojom::ShellClientFactory* factory_interface = factory.get();
  factory.set_connection_error_handler(
      base::Bind(&ApplicationManager::OnShellClientFactoryLost,
                 weak_ptr_factory_.GetWeakPtr(),
                 shell_client_factory_identity));
  shell_client_factories_[shell_client_factory_identity] = std::move(factory);
  return factory_interface;
}

void ApplicationManager::OnShellClientFactoryLost(const Identity& which) {
  // Remove the mapping.
  auto it = shell_client_factories_.find(which);
  DCHECK(it != shell_client_factories_.end());
  shell_client_factories_.erase(it);
}

void ApplicationManager::OnGotResolvedURL(
    scoped_ptr<ConnectToApplicationParams> params,
    const String& resolved_url,
    const String& file_url,
    const String& application_name,
    mojom::CapabilityFilterPtr base_filter) {
  // It's possible that when this manifest request was issued, another one was
  // already in-progress and completed by the time this one did, and so the
  // requested application may already be running.
  if (ConnectToRunningApplication(&params))
    return;

  Identity source = params->source(), target = params->target();
  mojom::ShellClientRequest request;
  ApplicationInstance* instance = CreateInstance(
      params->target(), params->on_application_end(), application_name,
      &request);
  instance->ConnectToClient(std::move(params));

  if (LoadWithLoader(target, &request))
    return;

  CHECK(!file_url.is_null() && !application_name.is_null() &&
        !base_filter.is_null());

  GURL resolved_gurl = resolved_url.To<GURL>();
  if (target.url().spec() != resolved_url) {
    // TODO(beng): this clobbers the CapabilityFilter passed via Connect().
    CapabilityFilter capability_filter = GetPermissiveCapabilityFilter();
    if (!base_filter.is_null())
      capability_filter = base_filter->filter.To<CapabilityFilter>();

    CreateShellClient(source, Identity(resolved_gurl, target.qualifier(),
                      capability_filter), target.url(), std::move(request));
  } else {
    bool start_sandboxed = false;
    base::FilePath path = util::UrlToFilePath(file_url.To<GURL>());
    scoped_ptr<NativeRunner> runner = native_runner_factory_->Create(path);
    runner->Start(path, start_sandboxed, std::move(request),
                  base::Bind(&ApplicationManager::ApplicationPIDAvailable,
                             weak_ptr_factory_.GetWeakPtr(), instance->id()),
                  base::Bind(&ApplicationManager::CleanupRunner,
                             weak_ptr_factory_.GetWeakPtr(), runner.get()));
    instance->SetNativeRunner(runner.get());
    native_runners_.push_back(std::move(runner));
  }
}

bool ApplicationManager::LoadWithLoader(const Identity& target,
                                        mojom::ShellClientRequest* request) {
  ApplicationLoader* loader = GetLoaderForURL(target.url());
  if (!loader)
    return false;
  loader->Load(target.url(), std::move(*request));
  return true;
}

ApplicationLoader* ApplicationManager::GetLoaderForURL(const GURL& url) {
  auto url_it = url_to_loader_.find(url);
  if (url_it != url_to_loader_.end())
    return url_it->second;
  return default_loader_.get();
}

void ApplicationManager::CleanupRunner(NativeRunner* runner) {
  for (auto it = native_runners_.begin(); it != native_runners_.end(); ++it) {
    if (it->get() == runner) {
      native_runners_.erase(it);
      return;
    }
  }
}

mojom::ApplicationInfoPtr ApplicationManager::CreateApplicationInfoForInstance(
    ApplicationInstance* instance) const {
  mojom::ApplicationInfoPtr info(mojom::ApplicationInfo::New());
  info->id = instance->id();
  info->url = instance->identity().url().spec();
  info->qualifier = instance->identity().qualifier();
  info->name = instance->application_name();
  if (instance->identity().url().spec() == "mojo://shell/")
    info->pid = base::Process::Current().Pid();
  else
    info->pid = instance->pid();
  return info;
}

}  // namespace shell
}  // namespace mojo