service_registry.cc revision f8ee788a64d60abd8f2d742a5fdedde054ecd910
1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "mojo/public/cpp/application/lib/service_registry.h"
6
7#include "mojo/public/cpp/application/application.h"
8#include "mojo/public/cpp/application/lib/service_connector.h"
9
10namespace mojo {
11namespace internal {
12
13ServiceRegistry::ServiceRegistry(Application* application)
14    : application_(application) {
15}
16
17ServiceRegistry::ServiceRegistry(
18    Application* application,
19    ScopedMessagePipeHandle service_provider_handle)
20        : application_(application) {
21  remote_service_provider_.Bind(service_provider_handle.Pass());
22  remote_service_provider_.set_client(this);
23}
24
25ServiceRegistry::~ServiceRegistry() {
26  for (NameToServiceConnectorMap::iterator i =
27           name_to_service_connector_.begin();
28       i != name_to_service_connector_.end(); ++i) {
29    delete i->second;
30  }
31  name_to_service_connector_.clear();
32}
33
34void ServiceRegistry::AddServiceConnector(
35    ServiceConnectorBase* service_connector) {
36  name_to_service_connector_[service_connector->name()] = service_connector;
37  service_connector->set_registry(this);
38}
39
40void ServiceRegistry::RemoveServiceConnector(
41    ServiceConnectorBase* service_connector) {
42  NameToServiceConnectorMap::iterator it =
43      name_to_service_connector_.find(service_connector->name());
44  assert(it != name_to_service_connector_.end());
45  delete it->second;
46  name_to_service_connector_.erase(it);
47  if (name_to_service_connector_.empty())
48    remote_service_provider_.reset();
49}
50
51void ServiceRegistry::BindRemoteServiceProvider(
52    ScopedMessagePipeHandle service_provider_handle) {
53  remote_service_provider_.Bind(service_provider_handle.Pass());
54  remote_service_provider_.set_client(this);
55}
56
57void ServiceRegistry::ConnectToService(const mojo::String& service_url,
58                                       const mojo::String& service_name,
59                                       ScopedMessagePipeHandle client_handle,
60                                       const mojo::String& requestor_url) {
61  if (!application_->AllowIncomingConnection(service_name, requestor_url)) {
62    client_handle.reset();
63    return;
64  }
65
66  internal::ServiceConnectorBase* service_connector =
67      name_to_service_connector_[service_name];
68  assert(service_connector);
69  // requestor_url is ignored because the service_connector stores the url
70  // of the requestor safely.
71  return service_connector->ConnectToService(
72      service_url, service_name, client_handle.Pass());
73}
74
75}  // namespace internal
76}  // namespace mojo
77