Upstream version 7.36.151.0
[platform/framework/web/crosswalk.git] / src / xwalk / application / browser / application.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/application/browser/application.h"
6
7 #include <string>
8
9 #include "base/files/file_enumerator.h"
10 #include "base/json/json_reader.h"
11 #include "base/macros.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_split.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "base/values.h"
17 #include "content/public/browser/web_contents.h"
18 #include "content/public/browser/render_process_host.h"
19 #include "content/public/browser/site_instance.h"
20 #include "net/base/net_util.h"
21 #include "xwalk/application/browser/application_service.h"
22 #include "xwalk/application/browser/application_storage.h"
23 #include "xwalk/application/browser/application_system.h"
24 #include "xwalk/application/common/application_manifest_constants.h"
25 #include "xwalk/application/common/constants.h"
26 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
27 #include "xwalk/runtime/browser/runtime.h"
28 #include "xwalk/runtime/browser/runtime_context.h"
29 #include "xwalk/runtime/browser/xwalk_runner.h"
30 #include "xwalk/runtime/common/xwalk_common_messages.h"
31
32 using content::RenderProcessHost;
33
34 namespace xwalk {
35
36 namespace keys = application_manifest_keys;
37 namespace widget_keys = application_widget_keys;
38
39 namespace {
40 const char* kDefaultWidgetEntryPage[] = {
41 "index.html",
42 "index.htm",
43 "index.svg",
44 "index.xhtml",
45 "index.xht"};
46
47 }  // namespace
48
49 namespace application {
50
51 Application::Application(
52     scoped_refptr<ApplicationData> data,
53     RuntimeContext* runtime_context,
54     Observer* observer)
55     : data_(data),
56       render_process_host_(NULL),
57       security_mode_enabled_(false),
58       runtime_context_(runtime_context),
59       observer_(observer),
60       entry_point_used_(Default),
61       weak_factory_(this) {
62   DCHECK(runtime_context_);
63   DCHECK(data_);
64   DCHECK(observer_);
65 }
66
67 Application::~Application() {
68   Terminate();
69   if (render_process_host_)
70     render_process_host_->RemoveObserver(this);
71 }
72
73 bool Application::Launch(const LaunchParams& launch_params) {
74   if (!runtimes_.empty()) {
75     LOG(ERROR) << "Attempt to launch app: " << id()
76                << " that was already launched.";
77     return false;
78   }
79
80   CHECK(!render_process_host_);
81
82   GURL url = GetStartURL(launch_params, &entry_point_used_);
83   if (!url.is_valid())
84     return false;
85
86   Runtime* runtime = Runtime::Create(
87       runtime_context_,
88       this, content::SiteInstance::CreateForURL(runtime_context_, url));
89   render_process_host_ = runtime->GetRenderProcessHost();
90   render_process_host_->AddObserver(this);
91   InitSecurityPolicy();
92   runtime->LoadURL(url);
93
94   NativeAppWindow::CreateParams params;
95   params.net_wm_pid = launch_params.launcher_pid;
96   if (data_->GetPackageType() == Package::WGT)
97     params.state = GetWindowShowStateWGT(launch_params);
98   else
99     params.state = GetWindowShowStateXPK(launch_params);
100   runtime->AttachWindow(params);
101
102   return true;
103 }
104
105 GURL Application::GetStartURL(const LaunchParams& params,
106                                   LaunchEntryPoint* used) {
107   if (params.entry_points & StartURLKey) {
108     GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
109     if (url.is_valid()) {
110       *used = StartURLKey;
111       return url;
112     }
113   }
114
115   if (params.entry_points & LaunchLocalPathKey) {
116     GURL url = GetURLFromRelativePathKey(
117         GetLaunchLocalPathKey(data_->GetPackageType()));
118     if (url.is_valid()) {
119       *used = LaunchLocalPathKey;
120       return url;
121     }
122   }
123
124   if (params.entry_points & URLKey) {
125     GURL url = GetURLFromURLKey();
126     if (url.is_valid()) {
127       *used = URLKey;
128       return url;
129     }
130   }
131
132   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
133   return GURL();
134 }
135
136 ui::WindowShowState Application::GetWindowShowStateWGT(
137     const LaunchParams& params) {
138   if (params.force_fullscreen)
139     return ui::SHOW_STATE_FULLSCREEN;
140
141   const Manifest* manifest = data_->GetManifest();
142   std::string view_modes_string;
143   if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
144     // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
145     // If the first user prefererence is 'fullscreen', set window show state
146     // FULLSCREEN, otherwise set the default window show state.
147     std::vector<std::string> modes;
148     base::SplitString(view_modes_string, ' ', &modes);
149     if (!modes.empty() && modes[0] == "fullscreen")
150       return ui::SHOW_STATE_FULLSCREEN;
151   }
152
153   return ui::SHOW_STATE_DEFAULT;
154 }
155
156 ui::WindowShowState Application::GetWindowShowStateXPK(
157     const LaunchParams& params) {
158   if (params.force_fullscreen)
159     return ui::SHOW_STATE_FULLSCREEN;
160
161   const Manifest* manifest = data_->GetManifest();
162   std::string display_string;
163   if (manifest->GetString(keys::kDisplay, &display_string)) {
164     // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
165     // values are supported.
166     if (display_string.find("fullscreen") != std::string::npos)
167       return ui::SHOW_STATE_FULLSCREEN;
168   }
169
170   return ui::SHOW_STATE_DEFAULT;
171 }
172
173 GURL Application::GetURLFromURLKey() {
174   const Manifest* manifest = data_->GetManifest();
175   std::string url_string;
176   if (!manifest->GetString(keys::kURLKey, &url_string))
177     return GURL();
178
179   return GURL(url_string);
180 }
181
182 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
183   const Manifest* manifest = data_->GetManifest();
184   std::string entry_page;
185   if (!manifest->GetString(key, &entry_page)
186       || entry_page.empty()) {
187     if (data_->GetPackageType() == Package::XPK)
188       return GURL();
189
190     base::ThreadRestrictions::SetIOAllowed(true);
191     base::FileEnumerator iter(data_->Path(), true,
192                               base::FileEnumerator::FILES,
193                               FILE_PATH_LITERAL("index.*"));
194     int priority = arraysize(kDefaultWidgetEntryPage);
195
196     for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
197       for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
198         if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
199             i < priority) {
200           entry_page = kDefaultWidgetEntryPage[i];
201           priority = i;
202         }
203       }
204     }
205
206     if (entry_page.empty())
207       return GURL();
208   }
209
210   return data_->GetResourceURL(entry_page);
211 }
212
213 void Application::Terminate() {
214   std::set<Runtime*> to_be_closed(runtimes_);
215   std::for_each(to_be_closed.begin(), to_be_closed.end(),
216                 std::mem_fun(&Runtime::Close));
217 }
218
219 int Application::GetRenderProcessHostID() const {
220   DCHECK(render_process_host_);
221   return render_process_host_->GetID();
222 }
223
224 void Application::OnRuntimeAdded(Runtime* runtime) {
225   DCHECK(runtime);
226   runtimes_.insert(runtime);
227 }
228
229 void Application::OnRuntimeRemoved(Runtime* runtime) {
230   DCHECK(runtime);
231   runtimes_.erase(runtime);
232
233   if (runtimes_.empty()) {
234 #if defined(OS_TIZEN_MOBILE)
235     runtime->CloseRootWindow();
236 #endif
237     base::MessageLoop::current()->PostTask(FROM_HERE,
238         base::Bind(&Application::NotifyTermination,
239                    weak_factory_.GetWeakPtr()));
240     return;
241   }
242 }
243
244 void Application::RenderProcessExited(RenderProcessHost* host,
245                                       base::ProcessHandle,
246                                       base::TerminationStatus,
247                                       int) {
248   DCHECK(render_process_host_ == host);
249   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
250   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
251 }
252
253 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
254   DCHECK(render_process_host_ == host);
255   render_process_host_ = NULL;
256 }
257
258 void Application::NotifyTermination() {
259   CHECK(!render_process_host_);
260   observer_->OnApplicationTerminated(this);
261 }
262
263 bool Application::UseExtension(const std::string& extension_name) const {
264   // TODO(Bai): Tells whether the application contains the specified extension
265   return true;
266 }
267
268 bool Application::RegisterPermissions(const std::string& extension_name,
269                                       const std::string& perm_table) {
270   // TODO(Bai): Parse the permission table and fill in the name_perm_map_
271   // The perm_table format is a simple JSON string, like
272   // [{"permission_name":"echo","apis":["add","remove","get"]}]
273   scoped_ptr<base::Value> root;
274   root.reset(base::JSONReader().ReadToValue(perm_table));
275   if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
276     return false;
277
278   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
279   if (permission_list->GetSize() == 0)
280     return false;
281
282   for (base::ListValue::const_iterator iter = permission_list->begin();
283       iter != permission_list->end(); ++iter) {
284     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
285         return false;
286
287     base::DictionaryValue* dict_val =
288         static_cast<base::DictionaryValue*>(*iter);
289     std::string permission_name;
290     if (!dict_val->GetString("permission_name", &permission_name))
291       return false;
292
293     base::ListValue* api_list = NULL;
294     if (!dict_val->GetList("apis", &api_list))
295       return false;
296
297     for (base::ListValue::const_iterator api_iter = api_list->begin();
298         api_iter != api_list->end(); ++api_iter) {
299       std::string api;
300       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
301           && (*api_iter)->GetAsString(&api)))
302         return false;
303       // register the permission and api
304       name_perm_map_[api] = permission_name;
305       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
306                  << " [API] " << api;
307     }
308   }
309
310   return true;
311 }
312
313 std::string Application::GetRegisteredPermissionName(
314     const std::string& extension_name,
315     const std::string& api_name) const {
316   std::map<std::string, std::string>::const_iterator iter =
317       name_perm_map_.find(api_name);
318   if (iter == name_perm_map_.end())
319     return std::string("");
320   return iter->second;
321 }
322
323 StoredPermission Application::GetPermission(PermissionType type,
324                                const std::string& permission_name) const {
325   if (type == SESSION_PERMISSION) {
326     StoredPermissionMap::const_iterator iter =
327         permission_map_.find(permission_name);
328     if (iter == permission_map_.end())
329       return UNDEFINED_STORED_PERM;
330     return iter->second;
331   }
332   if (type == PERSISTENT_PERMISSION) {
333     return data_->GetPermission(permission_name);
334   }
335   NOTREACHED();
336   return UNDEFINED_STORED_PERM;
337 }
338
339 bool Application::SetPermission(PermissionType type,
340                                 const std::string& permission_name,
341                                 StoredPermission perm) {
342   if (type == SESSION_PERMISSION) {
343     permission_map_[permission_name] = perm;
344     return true;
345   }
346   if (type == PERSISTENT_PERMISSION)
347     return data_->SetPermission(permission_name, perm);
348
349   NOTREACHED();
350   return false;
351 }
352
353 void Application::InitSecurityPolicy() {
354   if (data_->GetPackageType() != Package::WGT)
355     return;
356
357   const WARPInfo* info = static_cast<WARPInfo*>(
358       data_->GetManifestData(widget_keys::kAccessKey));
359   // Need to enable WARP mode by default.
360   if (!info) {
361     security_mode_enabled_ = true;
362     DCHECK(render_process_host_);
363     render_process_host_->Send(
364         new ViewMsg_EnableSecurityMode(
365             ApplicationData::GetBaseURLFromApplicationId(id()),
366             SecurityPolicy::WARP));
367     return;
368   }
369
370   const base::ListValue* whitelist = info->GetWARP();
371   for (base::ListValue::const_iterator it = whitelist->begin();
372        it != whitelist->end(); ++it) {
373     base::DictionaryValue* value = NULL;
374     (*it)->GetAsDictionary(&value);
375     std::string dest;
376     if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
377         dest.empty())
378       continue;
379     if (dest == "*") {
380       security_mode_enabled_ = false;
381       break;
382     }
383
384     GURL dest_url(dest);
385     // The default subdomains attrubute should be "false".
386     std::string subdomains = "false";
387     value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
388     AddSecurityPolicy(dest_url, (subdomains == "true"));
389     security_mode_enabled_ = true;
390   }
391   if (security_mode_enabled_) {
392     DCHECK(render_process_host_);
393     render_process_host_->Send(
394         new ViewMsg_EnableSecurityMode(
395             ApplicationData::GetBaseURLFromApplicationId(id()),
396             SecurityPolicy::WARP));
397   }
398 }
399
400 void Application::AddSecurityPolicy(const GURL& url, bool subdomains) {
401   GURL app_url = data_->URL();
402   DCHECK(render_process_host_);
403   render_process_host_->Send(
404       new ViewMsg_SetAccessWhiteList(
405           app_url, url, subdomains));
406   security_policy_.push_back(new SecurityPolicy(url, subdomains));
407 }
408
409 bool Application::CanRequestURL(const GURL& url) const {
410   if (!security_mode_enabled_)
411     return true;
412
413   // Only WGT package need to check the url request permission.
414   if (data_->GetPackageType() != Package::WGT)
415     return true;
416
417   // Always can request itself resources.
418   if (url.SchemeIs(application::kApplicationScheme) &&
419       url.host() == id())
420     return true;
421
422   for (unsigned i = 0; i < security_policy_.size(); ++i) {
423     const GURL& policy = security_policy_[i]->url();
424     bool subdomains = security_policy_[i]->subdomains();
425     bool is_host_matched = subdomains ?
426         url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
427     if (url.scheme() == policy.scheme() && is_host_matched)
428       return true;
429   }
430   return false;
431 }
432
433 }  // namespace application
434 }  // namespace xwalk