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.
5 #include "xwalk/application/browser/application.h"
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"
32 using content::RenderProcessHost;
36 namespace keys = application_manifest_keys;
37 namespace widget_keys = application_widget_keys;
40 const char* kDefaultWidgetEntryPage[] = {
49 namespace application {
51 Application::Application(
52 scoped_refptr<ApplicationData> data,
53 RuntimeContext* runtime_context,
56 render_process_host_(NULL),
57 security_mode_enabled_(false),
58 runtime_context_(runtime_context),
60 entry_point_used_(Default),
62 DCHECK(runtime_context_);
67 Application::~Application() {
69 if (render_process_host_)
70 render_process_host_->RemoveObserver(this);
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.";
80 CHECK(!render_process_host_);
82 GURL url = GetStartURL(launch_params, &entry_point_used_);
86 Runtime* runtime = Runtime::Create(
88 this, content::SiteInstance::CreateForURL(runtime_context_, url));
89 render_process_host_ = runtime->GetRenderProcessHost();
90 render_process_host_->AddObserver(this);
92 runtime->LoadURL(url);
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);
99 params.state = GetWindowShowStateXPK(launch_params);
100 runtime->AttachWindow(params);
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()) {
115 if (params.entry_points & LaunchLocalPathKey) {
116 GURL url = GetURLFromRelativePathKey(
117 GetLaunchLocalPathKey(data_->GetPackageType()));
118 if (url.is_valid()) {
119 *used = LaunchLocalPathKey;
124 if (params.entry_points & URLKey) {
125 GURL url = GetURLFromURLKey();
126 if (url.is_valid()) {
132 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
136 ui::WindowShowState Application::GetWindowShowStateWGT(
137 const LaunchParams& params) {
138 if (params.force_fullscreen)
139 return ui::SHOW_STATE_FULLSCREEN;
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;
153 return ui::SHOW_STATE_DEFAULT;
156 ui::WindowShowState Application::GetWindowShowStateXPK(
157 const LaunchParams& params) {
158 if (params.force_fullscreen)
159 return ui::SHOW_STATE_FULLSCREEN;
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;
170 return ui::SHOW_STATE_DEFAULT;
173 GURL Application::GetURLFromURLKey() {
174 const Manifest* manifest = data_->GetManifest();
175 std::string url_string;
176 if (!manifest->GetString(keys::kURLKey, &url_string))
179 return GURL(url_string);
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)
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);
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] &&
200 entry_page = kDefaultWidgetEntryPage[i];
206 if (entry_page.empty())
210 return data_->GetResourceURL(entry_page);
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));
219 int Application::GetRenderProcessHostID() const {
220 DCHECK(render_process_host_);
221 return render_process_host_->GetID();
224 void Application::OnRuntimeAdded(Runtime* runtime) {
226 runtimes_.insert(runtime);
229 void Application::OnRuntimeRemoved(Runtime* runtime) {
231 runtimes_.erase(runtime);
233 if (runtimes_.empty()) {
234 #if defined(OS_TIZEN_MOBILE)
235 runtime->CloseRootWindow();
237 base::MessageLoop::current()->PostTask(FROM_HERE,
238 base::Bind(&Application::NotifyTermination,
239 weak_factory_.GetWeakPtr()));
244 void Application::RenderProcessExited(RenderProcessHost* host,
246 base::TerminationStatus,
248 DCHECK(render_process_host_ == host);
249 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
250 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
253 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
254 DCHECK(render_process_host_ == host);
255 render_process_host_ = NULL;
258 void Application::NotifyTermination() {
259 CHECK(!render_process_host_);
260 observer_->OnApplicationTerminated(this);
263 bool Application::UseExtension(const std::string& extension_name) const {
264 // TODO(Bai): Tells whether the application contains the specified extension
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))
278 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
279 if (permission_list->GetSize() == 0)
282 for (base::ListValue::const_iterator iter = permission_list->begin();
283 iter != permission_list->end(); ++iter) {
284 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
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))
293 base::ListValue* api_list = NULL;
294 if (!dict_val->GetList("apis", &api_list))
297 for (base::ListValue::const_iterator api_iter = api_list->begin();
298 api_iter != api_list->end(); ++api_iter) {
300 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
301 && (*api_iter)->GetAsString(&api)))
303 // register the permission and api
304 name_perm_map_[api] = permission_name;
305 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
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("");
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;
332 if (type == PERSISTENT_PERMISSION) {
333 return data_->GetPermission(permission_name);
336 return UNDEFINED_STORED_PERM;
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;
346 if (type == PERSISTENT_PERMISSION)
347 return data_->SetPermission(permission_name, perm);
353 void Application::InitSecurityPolicy() {
354 if (data_->GetPackageType() != Package::WGT)
357 const WARPInfo* info = static_cast<WARPInfo*>(
358 data_->GetManifestData(widget_keys::kAccessKey));
359 // Need to enable WARP mode by default.
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));
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);
376 if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
380 security_mode_enabled_ = false;
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;
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));
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));
409 bool Application::CanRequestURL(const GURL& url) const {
410 if (!security_mode_enabled_)
413 // Only WGT package need to check the url request permission.
414 if (data_->GetPackageType() != Package::WGT)
417 // Always can request itself resources.
418 if (url.SchemeIs(application::kApplicationScheme) &&
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)
433 } // namespace application