64bc023399595a59137d94aea8d7deaa73994808
[platform/framework/web/crosswalk.git] / src / xwalk / extensions / browser / xwalk_extension_process_host.cc
1 // Copyright (c) 2013 Intel Corporation. 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 "xwalk/extensions/browser/xwalk_extension_process_host.h"
6
7 #include <string>
8
9 #include "base/command_line.h"
10 #include "base/logging.h"
11 #include "base/files/file_path.h"
12 #include "content/public/browser/browser_child_process_host.h"
13 #include "content/public/browser/browser_thread.h"
14 #include "content/public/browser/render_process_host.h"
15 #include "content/public/common/child_process_host.h"
16 #include "content/public/common/process_type.h"
17 #include "content/public/common/content_switches.h"
18 #include "content/public/common/sandboxed_process_launcher_delegate.h"
19 #include "ipc/ipc_message.h"
20 #include "ipc/ipc_switches.h"
21 #include "ipc/message_filter.h"
22 #include "xwalk/extensions/common/xwalk_extension_messages.h"
23 #include "xwalk/extensions/common/xwalk_extension_switches.h"
24 #include "xwalk/runtime/common/xwalk_switches.h"
25
26 using content::BrowserThread;
27
28 namespace xwalk {
29 namespace extensions {
30
31 // This filter is used by ExtensionProcessHost to intercept when Render Process
32 // ask for the Extension Channel handle (that is created by extension process).
33 class XWalkExtensionProcessHost::RenderProcessMessageFilter
34     : public IPC::MessageFilter {
35  public:
36   explicit RenderProcessMessageFilter(XWalkExtensionProcessHost* eph)
37       : eph_(eph) {}
38
39   // This exists to fulfill the requirement for delayed reply handling, since it
40   // needs to send a message back if the parameters couldn't be correctly read
41   // from the original message received. See DispatchDealyReplyWithSendParams().
42   bool Send(IPC::Message* message) {
43     if (eph_)
44       return eph_->render_process_host_->Send(message);
45     delete message;
46     return false;
47   }
48
49   void Invalidate() {
50     eph_ = NULL;
51   }
52
53  private:
54   // IPC::ChannelProxy::MessageFilter implementation.
55   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
56     bool handled = true;
57     IPC_BEGIN_MESSAGE_MAP(RenderProcessMessageFilter, message)
58       IPC_MESSAGE_HANDLER_DELAY_REPLY(
59           XWalkExtensionProcessHostMsg_GetExtensionProcessChannel,
60           OnGetExtensionProcessChannel)
61       IPC_MESSAGE_UNHANDLED(handled = false)
62     IPC_END_MESSAGE_MAP()
63     return handled;
64   }
65
66   void OnGetExtensionProcessChannel(IPC::Message* reply) {
67     scoped_ptr<IPC::Message> scoped_reply(reply);
68     if (eph_)
69       eph_->OnGetExtensionProcessChannel(scoped_reply.Pass());
70   }
71
72   virtual ~RenderProcessMessageFilter() {}
73
74   XWalkExtensionProcessHost* eph_;
75 };
76
77 class ExtensionSandboxedProcessLauncherDelegate
78     : public content::SandboxedProcessLauncherDelegate {
79  public:
80   explicit ExtensionSandboxedProcessLauncherDelegate(
81       content::ChildProcessHost* host)
82 #if defined(OS_POSIX)
83       : ipc_fd_(host->TakeClientFileDescriptor())
84 #endif
85   {}
86   virtual ~ExtensionSandboxedProcessLauncherDelegate() {}
87
88 #if defined(OS_WIN)
89   virtual bool ShouldSandbox() OVERRIDE {
90     return false;
91   }
92 #elif defined(OS_POSIX)
93   virtual int GetIpcFd() OVERRIDE {
94     return ipc_fd_;
95   }
96 #endif
97
98  private:
99 #if defined(OS_POSIX)
100   int ipc_fd_;
101 #endif
102
103   DISALLOW_COPY_AND_ASSIGN(ExtensionSandboxedProcessLauncherDelegate);
104 };
105
106 bool XWalkExtensionProcessHost::Delegate::OnRegisterPermissions(
107     int render_process_id,
108     const std::string& extension_name,
109     const std::string& perm_table) {
110   return false;
111 }
112
113 XWalkExtensionProcessHost::XWalkExtensionProcessHost(
114     content::RenderProcessHost* render_process_host,
115     const base::FilePath& external_extensions_path,
116     XWalkExtensionProcessHost::Delegate* delegate,
117     scoped_ptr<base::ValueMap> runtime_variables)
118     : ep_rp_channel_handle_(""),
119       render_process_host_(render_process_host),
120       render_process_message_filter_(new RenderProcessMessageFilter(this)),
121       external_extensions_path_(external_extensions_path),
122       is_extension_process_channel_ready_(false),
123       delegate_(delegate),
124       runtime_variables_(runtime_variables.Pass()) {
125   render_process_host_->GetChannel()->AddFilter(render_process_message_filter_);
126   BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
127       base::Bind(&XWalkExtensionProcessHost::StartProcess,
128       base::Unretained(this)));
129 }
130
131 XWalkExtensionProcessHost::~XWalkExtensionProcessHost() {
132   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
133   render_process_message_filter_->Invalidate();
134   StopProcess();
135 }
136
137 namespace {
138
139 void ToListValue(base::ValueMap* vm, base::ListValue* lv) {
140   lv->Clear();
141
142   for (base::ValueMap::iterator it = vm->begin(); it != vm->end(); it++) {
143     base::DictionaryValue* dv = new base::DictionaryValue();
144     dv->Set(it->first, it->second);
145     lv->Append(dv);
146   }
147 }
148
149 }  // namespace
150
151 void XWalkExtensionProcessHost::StartProcess() {
152   CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
153   CHECK(!process_ || !channel_);
154
155 #if defined(SHARED_PROCESS_MODE)
156 #if defined(OS_LINUX)
157     std::string channel_id =
158         IPC::Channel::GenerateVerifiedChannelID(std::string());
159     channel_ = IPC::Channel::CreateClient(channel_id, this);
160     if (!channel_->Connect())
161       NOTREACHED();
162     IPC::ChannelHandle channel_handle(channel_id,
163         base::FileDescriptor(channel_->TakeClientFileDescriptor(), true));
164     BrowserThread::PostTask(
165         BrowserThread::UI, FROM_HERE,
166         base::Bind(
167             &XWalkExtensionProcessHost::Delegate::OnExtensionProcessCreated,
168             base::Unretained(delegate_), render_process_host_->GetID(),
169             channel_handle));
170 #else
171     NOTIMPLEMENTED();
172 #endif  // #if defined(OS_LINUX)
173 #else
174     process_.reset(content::BrowserChildProcessHost::Create(
175         content::PROCESS_TYPE_CONTENT_END, this));
176
177     std::string channel_id = process_->GetHost()->CreateChannel();
178     CHECK(!channel_id.empty());
179
180     CommandLine::StringType extension_cmd_prefix;
181 #if defined(OS_POSIX)
182     const CommandLine &browser_command_line = *CommandLine::ForCurrentProcess();
183     extension_cmd_prefix = browser_command_line.GetSwitchValueNative(
184         switches::kXWalkExtensionCmdPrefix);
185 #endif
186
187 #if defined(OS_LINUX)
188     int flags = extension_cmd_prefix.empty() ?
189         content::ChildProcessHost::CHILD_ALLOW_SELF :
190         content::ChildProcessHost::CHILD_NORMAL;
191 #else
192     int flags = content::ChildProcessHost::CHILD_NORMAL;
193 #endif
194
195     base::FilePath exe_path = content::ChildProcessHost::GetChildPath(flags);
196     if (exe_path.empty())
197       return;
198
199     scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path));
200     cmd_line->AppendSwitchASCII(switches::kProcessType,
201                                 switches::kXWalkExtensionProcess);
202     cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
203     if (!extension_cmd_prefix.empty())
204       cmd_line->PrependWrapper(extension_cmd_prefix);
205
206     process_->Launch(
207         new ExtensionSandboxedProcessLauncherDelegate(process_->GetHost()),
208         cmd_line.release());
209 #endif  // #if defined(SHARED_PROCESS_MODE)
210
211   base::ListValue runtime_variables_lv;
212   ToListValue(&const_cast<base::ValueMap&>(*runtime_variables_),
213       &runtime_variables_lv);
214   Send(new XWalkExtensionProcessMsg_RegisterExtensions(
215         external_extensions_path_, runtime_variables_lv));
216 }
217
218 void XWalkExtensionProcessHost::StopProcess() {
219   if (process_)
220     process_.reset();
221   if (channel_)
222     channel_.reset();
223 }
224
225 void XWalkExtensionProcessHost::OnGetExtensionProcessChannel(
226     scoped_ptr<IPC::Message> reply) {
227   pending_reply_for_render_process_ = reply.Pass();
228   ReplyChannelHandleToRenderProcess();
229 }
230
231 bool XWalkExtensionProcessHost::OnMessageReceived(const IPC::Message& message) {
232   bool handled = true;
233   IPC_BEGIN_MESSAGE_MAP(XWalkExtensionProcessHost, message)
234     IPC_MESSAGE_HANDLER(
235         XWalkExtensionProcessHostMsg_RenderProcessChannelCreated,
236         OnRenderChannelCreated)
237     IPC_MESSAGE_HANDLER_DELAY_REPLY(
238         XWalkExtensionProcessHostMsg_CheckAPIAccessControl,
239         OnCheckAPIAccessControl)
240     IPC_MESSAGE_HANDLER(
241         XWalkExtensionProcessHostMsg_RegisterPermissions,
242         OnRegisterPermissions)
243     IPC_MESSAGE_UNHANDLED(handled = false)
244   IPC_END_MESSAGE_MAP()
245   return handled;
246 }
247
248 void XWalkExtensionProcessHost::OnChannelError() {
249   // This function is called just before
250   // BrowserChildProcessHostImpl::OnChildDisconnected gets called. Please refer
251   // to ChildProcessHostImpl::OnChannelError() from child_process_host_impl.cc.
252   // This means that content::BrowserChildProcessHost (process_, in our case)
253   // is about to delete its delegate, which is us!
254   // We should alert our XWalkExtensionProcessHost::Delegate, since it will
255   // most likely have a pointer to us that needs to be invalidated.
256
257   VLOG(1) << "\n\nExtensionProcess crashed";
258   if (delegate_)
259     delegate_->OnExtensionProcessDied(this, render_process_host_->GetID());
260 }
261
262 void XWalkExtensionProcessHost::OnProcessLaunched() {
263   VLOG(1) << "\n\nExtensionProcess was started!";
264 }
265
266 void XWalkExtensionProcessHost::OnRenderChannelCreated(
267     const IPC::ChannelHandle& handle) {
268   is_extension_process_channel_ready_ = true;
269   ep_rp_channel_handle_ = handle;
270   ReplyChannelHandleToRenderProcess();
271 }
272
273 void XWalkExtensionProcessHost::ReplyChannelHandleToRenderProcess() {
274   // Replying the channel handle to RP depends on two events:
275   // - EP already notified EPH that new channel was created (for RP<->EP).
276   // - RP already asked for the channel handle.
277   //
278   // The order for this events is not determined, so we call this function from
279   // both, and the second execution will send the reply.
280   if (!is_extension_process_channel_ready_
281       || !pending_reply_for_render_process_)
282     return;
283
284   XWalkExtensionProcessHostMsg_GetExtensionProcessChannel::WriteReplyParams(
285       pending_reply_for_render_process_.get(), ep_rp_channel_handle_);
286
287   render_process_host_->Send(pending_reply_for_render_process_.release());
288 }
289
290 void XWalkExtensionProcessHost::ReplyAccessControlToExtension(
291     IPC::Message* reply_msg,
292     RuntimePermission perm) {
293   XWalkExtensionProcessHostMsg_CheckAPIAccessControl
294       ::WriteReplyParams(reply_msg, perm);
295   Send(reply_msg);
296 }
297
298 void XWalkExtensionProcessHost::OnCheckAPIAccessControl(
299     const std::string& extension_name,
300     const std::string& api_name, IPC::Message* reply_msg) {
301   CHECK(delegate_);
302   delegate_->OnCheckAPIAccessControl(render_process_host_->GetID(),
303                                      extension_name, api_name,
304       base::Bind(&XWalkExtensionProcessHost::ReplyAccessControlToExtension,
305                  base::Unretained(this),
306                  reply_msg));
307 }
308
309 void XWalkExtensionProcessHost::OnRegisterPermissions(
310     const std::string& extension_name,
311     const std::string& perm_table, bool* result) {
312   CHECK(delegate_);
313   *result = delegate_->OnRegisterPermissions(
314       render_process_host_->GetID(), extension_name, perm_table);
315 }
316
317 bool XWalkExtensionProcessHost::Send(IPC::Message* msg) {
318   if (process_)
319     return process_->GetHost()->Send(msg);
320   if (channel_)
321     return channel_->Send(msg);
322   return false;
323 }
324
325 }  // namespace extensions
326 }  // namespace xwalk
327