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 "net/base/net_util.h"
18 #include "xwalk/application/browser/application_service.h"
19 #include "xwalk/application/browser/application_storage.h"
20 #include "xwalk/application/browser/application_system.h"
21 #include "xwalk/application/common/application_manifest_constants.h"
22 #include "xwalk/application/common/constants.h"
23 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
24 #include "xwalk/runtime/browser/runtime.h"
25 #include "xwalk/runtime/browser/runtime_context.h"
26 #include "xwalk/runtime/browser/xwalk_runner.h"
27 #include "xwalk/runtime/common/xwalk_common_messages.h"
29 using content::RenderProcessHost;
33 namespace keys = application_manifest_keys;
34 namespace widget_keys = application_widget_keys;
37 const char* kDefaultWidgetEntryPage[] = {
46 namespace application {
48 Application::Application(
49 scoped_refptr<ApplicationData> data,
50 RuntimeContext* runtime_context,
53 render_process_host_(NULL),
54 security_mode_enabled_(false),
55 runtime_context_(runtime_context),
57 entry_point_used_(Default),
59 DCHECK(runtime_context_);
64 Application::~Application() {
66 if (render_process_host_)
67 render_process_host_->RemoveObserver(this);
70 bool Application::Launch(const LaunchParams& launch_params) {
71 if (!runtimes_.empty()) {
72 LOG(ERROR) << "Attempt to launch app: " << id()
73 << " that was already launched.";
77 CHECK(!render_process_host_);
79 GURL url = GetStartURL(launch_params, &entry_point_used_);
83 Runtime* runtime = Runtime::Create(runtime_context_, this);
84 render_process_host_ = runtime->GetRenderProcessHost();
85 render_process_host_->AddObserver(this);
87 runtime->LoadURL(url);
89 NativeAppWindow::CreateParams params;
90 params.net_wm_pid = launch_params.launcher_pid;
91 params.state = GetWindowShowState(launch_params);
92 runtime->AttachWindow(params);
97 GURL Application::GetStartURL(const LaunchParams& params,
98 LaunchEntryPoint* used) {
99 if (params.entry_points & StartURLKey) {
100 GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
101 if (url.is_valid()) {
107 if (params.entry_points & LaunchLocalPathKey) {
108 GURL url = GetURLFromRelativePathKey(
109 GetLaunchLocalPathKey(data_->GetPackageType()));
110 if (url.is_valid()) {
111 *used = LaunchLocalPathKey;
116 if (params.entry_points & URLKey) {
117 GURL url = GetURLFromURLKey();
118 if (url.is_valid()) {
124 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
128 ui::WindowShowState Application::GetWindowShowState(
129 const LaunchParams& params) {
130 if (params.force_fullscreen)
131 return ui::SHOW_STATE_FULLSCREEN;
133 const Manifest* manifest = data_->GetManifest();
134 std::string display_string;
135 if (manifest->GetString(keys::kDisplay, &display_string)) {
136 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
137 // values are supported.
138 if (display_string.find("fullscreen") != std::string::npos)
139 return ui::SHOW_STATE_FULLSCREEN;
142 return ui::SHOW_STATE_DEFAULT;
145 GURL Application::GetURLFromURLKey() {
146 const Manifest* manifest = data_->GetManifest();
147 std::string url_string;
148 if (!manifest->GetString(keys::kURLKey, &url_string))
151 return GURL(url_string);
154 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
155 const Manifest* manifest = data_->GetManifest();
156 std::string entry_page;
157 if (!manifest->GetString(key, &entry_page)
158 || entry_page.empty()) {
159 if (data_->GetPackageType() == Package::XPK)
162 base::FileEnumerator iter(data_->Path(), true,
163 base::FileEnumerator::FILES,
164 FILE_PATH_LITERAL("index.*"));
165 int priority = arraysize(kDefaultWidgetEntryPage);
167 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
168 for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
169 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
171 entry_page = kDefaultWidgetEntryPage[i];
177 if (entry_page.empty())
181 return data_->GetResourceURL(entry_page);
184 void Application::Terminate() {
185 std::set<Runtime*> to_be_closed(runtimes_);
186 std::for_each(to_be_closed.begin(), to_be_closed.end(),
187 std::mem_fun(&Runtime::Close));
190 int Application::GetRenderProcessHostID() const {
191 DCHECK(render_process_host_);
192 return render_process_host_->GetID();
195 void Application::OnRuntimeAdded(Runtime* runtime) {
197 runtimes_.insert(runtime);
200 void Application::OnRuntimeRemoved(Runtime* runtime) {
202 runtimes_.erase(runtime);
204 if (runtimes_.empty()) {
205 #if defined(OS_TIZEN_MOBILE)
206 runtime->CloseRootWindow();
208 base::MessageLoop::current()->PostTask(FROM_HERE,
209 base::Bind(&Application::NotifyTermination,
210 weak_factory_.GetWeakPtr()));
215 void Application::RenderProcessExited(RenderProcessHost* host,
217 base::TerminationStatus,
219 DCHECK(render_process_host_ == host);
220 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
221 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
224 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
225 DCHECK(render_process_host_ == host);
226 render_process_host_ = NULL;
229 void Application::NotifyTermination() {
230 CHECK(!render_process_host_);
231 observer_->OnApplicationTerminated(this);
234 bool Application::UseExtension(const std::string& extension_name) const {
235 // TODO(Bai): Tells whether the application contains the specified extension
239 bool Application::RegisterPermissions(const std::string& extension_name,
240 const std::string& perm_table) {
241 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
242 // The perm_table format is a simple JSON string, like
243 // [{"permission_name":"echo","apis":["add","remove","get"]}]
244 scoped_ptr<base::Value> root;
245 root.reset(base::JSONReader().ReadToValue(perm_table));
246 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
249 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
250 if (permission_list->GetSize() == 0)
253 for (base::ListValue::const_iterator iter = permission_list->begin();
254 iter != permission_list->end(); ++iter) {
255 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
258 base::DictionaryValue* dict_val =
259 static_cast<base::DictionaryValue*>(*iter);
260 std::string permission_name;
261 if (!dict_val->GetString("permission_name", &permission_name))
264 base::ListValue* api_list = NULL;
265 if (!dict_val->GetList("apis", &api_list))
268 for (base::ListValue::const_iterator api_iter = api_list->begin();
269 api_iter != api_list->end(); ++api_iter) {
271 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
272 && (*api_iter)->GetAsString(&api)))
274 // register the permission and api
275 name_perm_map_[api] = permission_name;
276 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
284 std::string Application::GetRegisteredPermissionName(
285 const std::string& extension_name,
286 const std::string& api_name) const {
287 std::map<std::string, std::string>::const_iterator iter =
288 name_perm_map_.find(api_name);
289 if (iter == name_perm_map_.end())
290 return std::string("");
294 StoredPermission Application::GetPermission(PermissionType type,
295 std::string& permission_name) const {
296 if (type == SESSION_PERMISSION) {
297 StoredPermissionMap::const_iterator iter =
298 permission_map_.find(permission_name);
299 if (iter == permission_map_.end())
300 return UNDEFINED_STORED_PERM;
303 if (type == PERSISTENT_PERMISSION) {
304 return data_->GetPermission(permission_name);
307 return UNDEFINED_STORED_PERM;
310 bool Application::SetPermission(PermissionType type,
311 const std::string& permission_name,
312 StoredPermission perm) {
313 if (type == SESSION_PERMISSION) {
314 permission_map_[permission_name] = perm;
317 if (type == PERSISTENT_PERMISSION)
318 return data_->SetPermission(permission_name, perm);
324 void Application::InitSecurityPolicy() {
325 if (data_->GetPackageType() != Package::WGT)
328 const WARPInfo* info = static_cast<WARPInfo*>(
329 data_->GetManifestData(widget_keys::kAccessKey));
330 // FIXME(xinchao): Need to enable WARP mode by default.
334 const base::ListValue* whitelist = info->GetWARP();
335 for (base::ListValue::const_iterator it = whitelist->begin();
336 it != whitelist->end(); ++it) {
337 base::DictionaryValue* value = NULL;
338 (*it)->GetAsDictionary(&value);
340 if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
344 security_mode_enabled_ = false;
349 // The default subdomains attrubute should be "false".
350 std::string subdomains = "false";
351 value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
352 AddSecurityPolicy(dest_url, (subdomains == "true"));
353 security_mode_enabled_ = true;
355 if (security_mode_enabled_) {
356 DCHECK(render_process_host_);
357 render_process_host_->Send(
358 new ViewMsg_EnableSecurityMode(
359 ApplicationData::GetBaseURLFromApplicationId(id()),
360 SecurityPolicy::WARP));
364 void Application::AddSecurityPolicy(const GURL& url, bool subdomains) {
365 GURL app_url = data_->URL();
366 DCHECK(render_process_host_);
367 render_process_host_->Send(
368 new ViewMsg_SetAccessWhiteList(
369 app_url, url, subdomains));
370 security_policy_.push_back(new SecurityPolicy(url, subdomains));
373 bool Application::CanRequestURL(const GURL& url) const {
374 if (!security_mode_enabled_)
377 // Only WGT package need to check the url request permission.
378 if (data_->GetPackageType() != Package::WGT)
381 // Always can request itself resources.
382 if (url.SchemeIs(application::kApplicationScheme) &&
386 for (unsigned i = 0; i < security_policy_.size(); ++i) {
387 const GURL& policy = security_policy_[i]->url();
388 bool subdomains = security_policy_[i]->subdomains();
389 bool is_host_matched = subdomains ?
390 url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
391 if (url.scheme() == policy.scheme() && is_host_matched)
397 } // namespace application