Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / mojo / shell / dbus_service_loader_linux.cc
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/shell/dbus_service_loader_linux.h"
6
7 #include <string>
8
9 #include "base/command_line.h"
10 #include "base/location.h"
11 #include "base/logging.h"
12 #include "base/task_runner_util.h"
13 #include "base/threading/thread_restrictions.h"
14 #include "dbus/bus.h"
15 #include "dbus/file_descriptor.h"
16 #include "dbus/message.h"
17 #include "dbus/object_path.h"
18 #include "dbus/object_proxy.h"
19 #include "mojo/dbus/dbus_external_service.h"
20 #include "mojo/embedder/channel_init.h"
21 #include "mojo/embedder/platform_channel_pair.h"
22 #include "mojo/shell/context.h"
23 #include "mojo/shell/external_service.mojom.h"
24 #include "mojo/shell/keep_alive.h"
25
26 namespace mojo {
27 namespace shell {
28
29 // Manages the connection to a single externally-running service.
30 class DBusServiceLoader::LoadContext {
31  public:
32   // Kicks off the attempt to bootstrap a connection to the externally-running
33   // service specified by url_.
34   // Creates a MessagePipe and passes one end over DBus to the service. Then,
35   // calls ExternalService::Activate(ShellHandle) over the now-shared pipe.
36   LoadContext(DBusServiceLoader* loader,
37               const scoped_refptr<dbus::Bus>& bus,
38               const GURL& url,
39               ScopedMessagePipeHandle service_provider_handle)
40       : loader_(loader),
41         bus_(bus),
42         service_dbus_proxy_(NULL),
43         url_(url),
44         service_provider_handle_(service_provider_handle.Pass()),
45         keep_alive_(loader->context_) {
46     base::PostTaskAndReplyWithResult(
47         loader_->context_->task_runners()->io_runner(),
48         FROM_HERE,
49         base::Bind(&LoadContext::CreateChannelOnIOThread,
50                    base::Unretained(this)),
51         base::Bind(&LoadContext::ConnectChannel, base::Unretained(this)));
52   }
53
54   virtual ~LoadContext() {
55   }
56
57  private:
58   // Sets up a pipe to share with the externally-running service and returns
59   // the endpoint that should be sent over DBus.
60   // The FD for the endpoint must be validated on an IO thread.
61   scoped_ptr<dbus::FileDescriptor> CreateChannelOnIOThread() {
62     base::ThreadRestrictions::AssertIOAllowed();
63     CHECK(bus_->Connect());
64     CHECK(bus_->SetUpAsyncOperations());
65
66     embedder::PlatformChannelPair channel_pair;
67     channel_init_.reset(new embedder::ChannelInit);
68     mojo::ScopedMessagePipeHandle bootstrap_message_pipe =
69         channel_init_->Init(channel_pair.PassServerHandle().release().fd,
70                             loader_->context_->task_runners()->io_runner());
71     CHECK(bootstrap_message_pipe.is_valid());
72
73     external_service_.Bind(bootstrap_message_pipe.Pass());
74
75     scoped_ptr<dbus::FileDescriptor> client_fd(new dbus::FileDescriptor);
76     client_fd->PutValue(channel_pair.PassClientHandle().release().fd);
77     client_fd->CheckValidity();  // Must be run on an IO thread.
78     return client_fd.Pass();
79   }
80
81   // Sends client_fd over to the externally-running service. If that
82   // attempt is successful, the service will then be "activated" by
83   // sending it a ShellHandle.
84   void ConnectChannel(scoped_ptr<dbus::FileDescriptor> client_fd) {
85     size_t first_slash = url_.path().find_first_of('/');
86     DCHECK_NE(first_slash, std::string::npos);
87
88     const std::string service_name = url_.path().substr(0, first_slash);
89     const std::string object_path =  url_.path().substr(first_slash);
90     service_dbus_proxy_ =
91         bus_->GetObjectProxy(service_name, dbus::ObjectPath(object_path));
92
93     dbus::MethodCall call(kMojoDBusInterface, kMojoDBusConnectMethod);
94     dbus::MessageWriter writer(&call);
95     writer.AppendFileDescriptor(*client_fd.get());
96
97     // TODO(cmasone): handle errors!
98     service_dbus_proxy_->CallMethod(
99         &call,
100         dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
101         base::Bind(&LoadContext::ActivateService, base::Unretained(this)));
102   }
103
104   // Sends a ShellHandle over to the now-connected externally-running service,
105   // using the Mojo ExternalService API.
106   void ActivateService(dbus::Response* response) {
107     external_service_->Activate(
108         mojo::ScopedMessagePipeHandle(
109             mojo::MessagePipeHandle(
110                 service_provider_handle_.release().value())));
111   }
112
113   // Should the ExternalService disappear completely, destroy connection state.
114   // NB: This triggers off of the service disappearing from
115   // DBus. Perhaps there's a way to watch at the Mojo layer instead,
116   // and that would be superior?
117   void HandleNameOwnerChanged(const std::string& old_owner,
118                               const std::string& new_owner) {
119     DCHECK(loader_->context_->task_runners()->ui_runner()->
120            BelongsToCurrentThread());
121
122     if (new_owner.empty()) {
123       loader_->context_->task_runners()->ui_runner()->PostTask(
124           FROM_HERE,
125           base::Bind(&DBusServiceLoader::ForgetService,
126                      base::Unretained(loader_), url_));
127     }
128   }
129
130   DBusServiceLoader* const loader_;
131   scoped_refptr<dbus::Bus> bus_;
132   dbus::ObjectProxy* service_dbus_proxy_;  // Owned by bus_;
133   const GURL url_;
134   ScopedMessagePipeHandle service_provider_handle_;
135   KeepAlive keep_alive_;
136   scoped_ptr<embedder::ChannelInit> channel_init_;
137   ExternalServicePtr external_service_;
138
139   DISALLOW_COPY_AND_ASSIGN(LoadContext);
140 };
141
142 DBusServiceLoader::DBusServiceLoader(Context* context) : context_(context) {
143   dbus::Bus::Options options;
144   options.bus_type = dbus::Bus::SESSION;
145   options.dbus_task_runner = context_->task_runners()->io_runner();
146   bus_ = new dbus::Bus(options);
147 }
148
149 DBusServiceLoader::~DBusServiceLoader() {
150   DCHECK(url_to_load_context_.empty());
151 }
152
153 void DBusServiceLoader::LoadService(ServiceManager* manager,
154                                     const GURL& url,
155                                     ScopedMessagePipeHandle service_handle) {
156   DCHECK(url.SchemeIs("dbus"));
157   DCHECK(url_to_load_context_.find(url) == url_to_load_context_.end());
158   url_to_load_context_[url] =
159       new LoadContext(this, bus_, url, service_handle.Pass());
160 }
161
162 void DBusServiceLoader::OnServiceError(ServiceManager* manager,
163                                        const GURL& url) {
164   // TODO(cmasone): Anything at all in this method here.
165 }
166
167 void DBusServiceLoader::ForgetService(const GURL& url) {
168   DCHECK(context_->task_runners()->ui_runner()->BelongsToCurrentThread());
169   DVLOG(2) << "Forgetting service (url: " << url << ")";
170
171   LoadContextMap::iterator it = url_to_load_context_.find(url);
172   DCHECK(it != url_to_load_context_.end()) << url;
173
174   LoadContext* doomed = it->second;
175   url_to_load_context_.erase(it);
176
177   delete doomed;
178 }
179
180 }  // namespace shell
181 }  // namespace mojo