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/values.h"
15 #include "content/public/browser/web_contents.h"
16 #include "content/public/browser/render_process_host.h"
17 #include "content/public/browser/site_instance.h"
18 #include "net/base/net_util.h"
19 #include "xwalk/application/browser/application_service.h"
20 #include "xwalk/application/browser/application_storage.h"
21 #include "xwalk/application/browser/application_system.h"
22 #include "xwalk/application/common/application_manifest_constants.h"
23 #include "xwalk/application/common/constants.h"
24 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
25 #include "xwalk/runtime/browser/runtime.h"
26 #include "xwalk/runtime/browser/runtime_context.h"
27 #include "xwalk/runtime/browser/xwalk_runner.h"
28 #include "xwalk/runtime/common/xwalk_common_messages.h"
30 using content::RenderProcessHost;
34 namespace keys = application_manifest_keys;
35 namespace widget_keys = application_widget_keys;
38 const char* kDefaultWidgetEntryPage[] = {
47 namespace application {
49 Application::Application(
50 scoped_refptr<ApplicationData> data,
51 RuntimeContext* runtime_context,
54 render_process_host_(NULL),
55 security_mode_enabled_(false),
56 runtime_context_(runtime_context),
58 entry_point_used_(Default),
60 DCHECK(runtime_context_);
65 Application::~Application() {
67 if (render_process_host_)
68 render_process_host_->RemoveObserver(this);
71 bool Application::Launch(const LaunchParams& launch_params) {
72 if (!runtimes_.empty()) {
73 LOG(ERROR) << "Attempt to launch app: " << id()
74 << " that was already launched.";
78 CHECK(!render_process_host_);
80 GURL url = GetStartURL(launch_params, &entry_point_used_);
84 Runtime* runtime = Runtime::Create(
86 this, content::SiteInstance::CreateForURL(runtime_context_, url));
87 render_process_host_ = runtime->GetRenderProcessHost();
88 render_process_host_->AddObserver(this);
90 runtime->LoadURL(url);
92 NativeAppWindow::CreateParams params;
93 params.net_wm_pid = launch_params.launcher_pid;
94 params.state = GetWindowShowState(launch_params);
95 runtime->AttachWindow(params);
100 GURL Application::GetStartURL(const LaunchParams& params,
101 LaunchEntryPoint* used) {
102 if (params.entry_points & StartURLKey) {
103 GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
104 if (url.is_valid()) {
110 if (params.entry_points & LaunchLocalPathKey) {
111 GURL url = GetURLFromRelativePathKey(
112 GetLaunchLocalPathKey(data_->GetPackageType()));
113 if (url.is_valid()) {
114 *used = LaunchLocalPathKey;
119 if (params.entry_points & URLKey) {
120 GURL url = GetURLFromURLKey();
121 if (url.is_valid()) {
127 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
131 ui::WindowShowState Application::GetWindowShowState(
132 const LaunchParams& params) {
133 if (params.force_fullscreen)
134 return ui::SHOW_STATE_FULLSCREEN;
136 const Manifest* manifest = data_->GetManifest();
137 std::string display_string;
138 if (manifest->GetString(keys::kDisplay, &display_string)) {
139 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
140 // values are supported.
141 if (display_string.find("fullscreen") != std::string::npos)
142 return ui::SHOW_STATE_FULLSCREEN;
145 return ui::SHOW_STATE_DEFAULT;
148 GURL Application::GetURLFromURLKey() {
149 const Manifest* manifest = data_->GetManifest();
150 std::string url_string;
151 if (!manifest->GetString(keys::kURLKey, &url_string))
154 return GURL(url_string);
157 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
158 const Manifest* manifest = data_->GetManifest();
159 std::string entry_page;
160 if (!manifest->GetString(key, &entry_page)
161 || entry_page.empty()) {
162 if (data_->GetPackageType() == Package::XPK)
165 base::ThreadRestrictions::SetIOAllowed(true);
166 base::FileEnumerator iter(data_->Path(), true,
167 base::FileEnumerator::FILES,
168 FILE_PATH_LITERAL("index.*"));
169 int priority = arraysize(kDefaultWidgetEntryPage);
171 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
172 for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
173 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
175 entry_page = kDefaultWidgetEntryPage[i];
181 if (entry_page.empty())
185 return data_->GetResourceURL(entry_page);
188 void Application::Terminate() {
189 std::set<Runtime*> to_be_closed(runtimes_);
190 std::for_each(to_be_closed.begin(), to_be_closed.end(),
191 std::mem_fun(&Runtime::Close));
194 int Application::GetRenderProcessHostID() const {
195 DCHECK(render_process_host_);
196 return render_process_host_->GetID();
199 void Application::OnRuntimeAdded(Runtime* runtime) {
201 runtimes_.insert(runtime);
204 void Application::OnRuntimeRemoved(Runtime* runtime) {
206 runtimes_.erase(runtime);
208 if (runtimes_.empty()) {
209 #if defined(OS_TIZEN_MOBILE)
210 runtime->CloseRootWindow();
212 base::MessageLoop::current()->PostTask(FROM_HERE,
213 base::Bind(&Application::NotifyTermination,
214 weak_factory_.GetWeakPtr()));
219 void Application::RenderProcessExited(RenderProcessHost* host,
221 base::TerminationStatus,
223 DCHECK(render_process_host_ == host);
224 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
225 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
228 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
229 DCHECK(render_process_host_ == host);
230 render_process_host_ = NULL;
233 void Application::NotifyTermination() {
234 CHECK(!render_process_host_);
235 observer_->OnApplicationTerminated(this);
238 bool Application::UseExtension(const std::string& extension_name) const {
239 // TODO(Bai): Tells whether the application contains the specified extension
243 bool Application::RegisterPermissions(const std::string& extension_name,
244 const std::string& perm_table) {
245 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
246 // The perm_table format is a simple JSON string, like
247 // [{"permission_name":"echo","apis":["add","remove","get"]}]
248 scoped_ptr<base::Value> root;
249 root.reset(base::JSONReader().ReadToValue(perm_table));
250 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
253 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
254 if (permission_list->GetSize() == 0)
257 for (base::ListValue::const_iterator iter = permission_list->begin();
258 iter != permission_list->end(); ++iter) {
259 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
262 base::DictionaryValue* dict_val =
263 static_cast<base::DictionaryValue*>(*iter);
264 std::string permission_name;
265 if (!dict_val->GetString("permission_name", &permission_name))
268 base::ListValue* api_list = NULL;
269 if (!dict_val->GetList("apis", &api_list))
272 for (base::ListValue::const_iterator api_iter = api_list->begin();
273 api_iter != api_list->end(); ++api_iter) {
275 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
276 && (*api_iter)->GetAsString(&api)))
278 // register the permission and api
279 name_perm_map_[api] = permission_name;
280 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
288 std::string Application::GetRegisteredPermissionName(
289 const std::string& extension_name,
290 const std::string& api_name) const {
291 std::map<std::string, std::string>::const_iterator iter =
292 name_perm_map_.find(api_name);
293 if (iter == name_perm_map_.end())
294 return std::string("");
298 StoredPermission Application::GetPermission(PermissionType type,
299 std::string& permission_name) const {
300 if (type == SESSION_PERMISSION) {
301 StoredPermissionMap::const_iterator iter =
302 permission_map_.find(permission_name);
303 if (iter == permission_map_.end())
304 return UNDEFINED_STORED_PERM;
307 if (type == PERSISTENT_PERMISSION) {
308 return data_->GetPermission(permission_name);
311 return UNDEFINED_STORED_PERM;
314 bool Application::SetPermission(PermissionType type,
315 const std::string& permission_name,
316 StoredPermission perm) {
317 if (type == SESSION_PERMISSION) {
318 permission_map_[permission_name] = perm;
321 if (type == PERSISTENT_PERMISSION)
322 return data_->SetPermission(permission_name, perm);
328 void Application::InitSecurityPolicy() {
329 if (data_->GetPackageType() != Package::WGT)
332 const WARPInfo* info = static_cast<WARPInfo*>(
333 data_->GetManifestData(widget_keys::kAccessKey));
334 // Need to enable WARP mode by default.
336 security_mode_enabled_ = true;
337 DCHECK(render_process_host_);
338 render_process_host_->Send(
339 new ViewMsg_EnableSecurityMode(
340 ApplicationData::GetBaseURLFromApplicationId(id()),
341 SecurityPolicy::WARP));
345 const base::ListValue* whitelist = info->GetWARP();
346 for (base::ListValue::const_iterator it = whitelist->begin();
347 it != whitelist->end(); ++it) {
348 base::DictionaryValue* value = NULL;
349 (*it)->GetAsDictionary(&value);
351 if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
355 security_mode_enabled_ = false;
360 // The default subdomains attrubute should be "false".
361 std::string subdomains = "false";
362 value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
363 AddSecurityPolicy(dest_url, (subdomains == "true"));
364 security_mode_enabled_ = true;
366 if (security_mode_enabled_) {
367 DCHECK(render_process_host_);
368 render_process_host_->Send(
369 new ViewMsg_EnableSecurityMode(
370 ApplicationData::GetBaseURLFromApplicationId(id()),
371 SecurityPolicy::WARP));
375 void Application::AddSecurityPolicy(const GURL& url, bool subdomains) {
376 GURL app_url = data_->URL();
377 DCHECK(render_process_host_);
378 render_process_host_->Send(
379 new ViewMsg_SetAccessWhiteList(
380 app_url, url, subdomains));
381 security_policy_.push_back(new SecurityPolicy(url, subdomains));
384 bool Application::CanRequestURL(const GURL& url) const {
385 if (!security_mode_enabled_)
388 // Only WGT package need to check the url request permission.
389 if (data_->GetPackageType() != Package::WGT)
392 // Always can request itself resources.
393 if (url.SchemeIs(application::kApplicationScheme) &&
397 for (unsigned i = 0; i < security_policy_.size(); ++i) {
398 const GURL& policy = security_policy_[i]->url();
399 bool subdomains = security_policy_[i]->subdomains();
400 bool is_host_matched = subdomains ?
401 url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
402 if (url.scheme() == policy.scheme() && is_host_matched)
408 } // namespace application