Upstream version 7.36.149.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/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"
29
30 using content::RenderProcessHost;
31
32 namespace xwalk {
33
34 namespace keys = application_manifest_keys;
35 namespace widget_keys = application_widget_keys;
36
37 namespace {
38 const char* kDefaultWidgetEntryPage[] = {
39 "index.html",
40 "index.htm",
41 "index.svg",
42 "index.xhtml",
43 "index.xht"};
44
45 }  // namespace
46
47 namespace application {
48
49 Application::Application(
50     scoped_refptr<ApplicationData> data,
51     RuntimeContext* runtime_context,
52     Observer* observer)
53     : data_(data),
54       render_process_host_(NULL),
55       security_mode_enabled_(false),
56       runtime_context_(runtime_context),
57       observer_(observer),
58       entry_point_used_(Default),
59       weak_factory_(this) {
60   DCHECK(runtime_context_);
61   DCHECK(data_);
62   DCHECK(observer_);
63 }
64
65 Application::~Application() {
66   Terminate();
67   if (render_process_host_)
68     render_process_host_->RemoveObserver(this);
69 }
70
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.";
75     return false;
76   }
77
78   CHECK(!render_process_host_);
79
80   GURL url = GetStartURL(launch_params, &entry_point_used_);
81   if (!url.is_valid())
82     return false;
83
84   Runtime* runtime = Runtime::Create(
85       runtime_context_,
86       this, content::SiteInstance::CreateForURL(runtime_context_, url));
87   render_process_host_ = runtime->GetRenderProcessHost();
88   render_process_host_->AddObserver(this);
89   InitSecurityPolicy();
90   runtime->LoadURL(url);
91
92   NativeAppWindow::CreateParams params;
93   params.net_wm_pid = launch_params.launcher_pid;
94   params.state = GetWindowShowState(launch_params);
95   runtime->AttachWindow(params);
96
97   return true;
98 }
99
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()) {
105       *used = StartURLKey;
106       return url;
107     }
108   }
109
110   if (params.entry_points & LaunchLocalPathKey) {
111     GURL url = GetURLFromRelativePathKey(
112         GetLaunchLocalPathKey(data_->GetPackageType()));
113     if (url.is_valid()) {
114       *used = LaunchLocalPathKey;
115       return url;
116     }
117   }
118
119   if (params.entry_points & URLKey) {
120     GURL url = GetURLFromURLKey();
121     if (url.is_valid()) {
122       *used = URLKey;
123       return url;
124     }
125   }
126
127   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
128   return GURL();
129 }
130
131 ui::WindowShowState Application::GetWindowShowState(
132     const LaunchParams& params) {
133   if (params.force_fullscreen)
134     return ui::SHOW_STATE_FULLSCREEN;
135
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;
143   }
144
145   return ui::SHOW_STATE_DEFAULT;
146 }
147
148 GURL Application::GetURLFromURLKey() {
149   const Manifest* manifest = data_->GetManifest();
150   std::string url_string;
151   if (!manifest->GetString(keys::kURLKey, &url_string))
152     return GURL();
153
154   return GURL(url_string);
155 }
156
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)
163       return GURL();
164
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);
170
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] &&
174             i < priority) {
175           entry_page = kDefaultWidgetEntryPage[i];
176           priority = i;
177         }
178       }
179     }
180
181     if (entry_page.empty())
182       return GURL();
183   }
184
185   return data_->GetResourceURL(entry_page);
186 }
187
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));
192 }
193
194 int Application::GetRenderProcessHostID() const {
195   DCHECK(render_process_host_);
196   return render_process_host_->GetID();
197 }
198
199 void Application::OnRuntimeAdded(Runtime* runtime) {
200   DCHECK(runtime);
201   runtimes_.insert(runtime);
202 }
203
204 void Application::OnRuntimeRemoved(Runtime* runtime) {
205   DCHECK(runtime);
206   runtimes_.erase(runtime);
207
208   if (runtimes_.empty()) {
209 #if defined(OS_TIZEN_MOBILE)
210     runtime->CloseRootWindow();
211 #endif
212     base::MessageLoop::current()->PostTask(FROM_HERE,
213         base::Bind(&Application::NotifyTermination,
214                    weak_factory_.GetWeakPtr()));
215     return;
216   }
217 }
218
219 void Application::RenderProcessExited(RenderProcessHost* host,
220                                       base::ProcessHandle,
221                                       base::TerminationStatus,
222                                       int) {
223   DCHECK(render_process_host_ == host);
224   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
225   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
226 }
227
228 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
229   DCHECK(render_process_host_ == host);
230   render_process_host_ = NULL;
231 }
232
233 void Application::NotifyTermination() {
234   CHECK(!render_process_host_);
235   observer_->OnApplicationTerminated(this);
236 }
237
238 bool Application::UseExtension(const std::string& extension_name) const {
239   // TODO(Bai): Tells whether the application contains the specified extension
240   return true;
241 }
242
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))
251     return false;
252
253   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
254   if (permission_list->GetSize() == 0)
255     return false;
256
257   for (base::ListValue::const_iterator iter = permission_list->begin();
258       iter != permission_list->end(); ++iter) {
259     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
260         return false;
261
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))
266       return false;
267
268     base::ListValue* api_list = NULL;
269     if (!dict_val->GetList("apis", &api_list))
270       return false;
271
272     for (base::ListValue::const_iterator api_iter = api_list->begin();
273         api_iter != api_list->end(); ++api_iter) {
274       std::string api;
275       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
276           && (*api_iter)->GetAsString(&api)))
277         return false;
278       // register the permission and api
279       name_perm_map_[api] = permission_name;
280       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
281                  << " [API] " << api;
282     }
283   }
284
285   return true;
286 }
287
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("");
295   return iter->second;
296 }
297
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;
305     return iter->second;
306   }
307   if (type == PERSISTENT_PERMISSION) {
308     return data_->GetPermission(permission_name);
309   }
310   NOTREACHED();
311   return UNDEFINED_STORED_PERM;
312 }
313
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;
319     return true;
320   }
321   if (type == PERSISTENT_PERMISSION)
322     return data_->SetPermission(permission_name, perm);
323
324   NOTREACHED();
325   return false;
326 }
327
328 void Application::InitSecurityPolicy() {
329   if (data_->GetPackageType() != Package::WGT)
330     return;
331
332   const WARPInfo* info = static_cast<WARPInfo*>(
333       data_->GetManifestData(widget_keys::kAccessKey));
334   // Need to enable WARP mode by default.
335   if (!info) {
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));
342     return;
343   }
344
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);
350     std::string dest;
351     if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
352         dest.empty())
353       continue;
354     if (dest == "*") {
355       security_mode_enabled_ = false;
356       break;
357     }
358
359     GURL dest_url(dest);
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;
365   }
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));
372   }
373 }
374
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));
382 }
383
384 bool Application::CanRequestURL(const GURL& url) const {
385   if (!security_mode_enabled_)
386     return true;
387
388   // Only WGT package need to check the url request permission.
389   if (data_->GetPackageType() != Package::WGT)
390     return true;
391
392   // Always can request itself resources.
393   if (url.SchemeIs(application::kApplicationScheme) &&
394       url.host() == id())
395     return true;
396
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)
403       return true;
404   }
405   return false;
406 }
407
408 }  // namespace application
409 }  // namespace xwalk