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