Upstream version 7.35.141.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 "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"
28
29 using content::RenderProcessHost;
30
31 namespace xwalk {
32
33 namespace keys = application_manifest_keys;
34 namespace widget_keys = application_widget_keys;
35
36 namespace {
37 const char* kDefaultWidgetEntryPage[] = {
38 "index.html",
39 "index.htm",
40 "index.svg",
41 "index.xhtml",
42 "index.xht"};
43
44 }  // namespace
45
46 namespace application {
47
48 Application::Application(
49     scoped_refptr<ApplicationData> data,
50     RuntimeContext* runtime_context,
51     Observer* observer)
52     : data_(data),
53       render_process_host_(NULL),
54       security_mode_enabled_(false),
55       runtime_context_(runtime_context),
56       observer_(observer),
57       entry_point_used_(Default),
58       weak_factory_(this) {
59   DCHECK(runtime_context_);
60   DCHECK(data_);
61   DCHECK(observer_);
62 }
63
64 Application::~Application() {
65   Terminate();
66   if (render_process_host_)
67     render_process_host_->RemoveObserver(this);
68 }
69
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.";
74     return false;
75   }
76
77   CHECK(!render_process_host_);
78
79   GURL url = GetStartURL(launch_params, &entry_point_used_);
80   if (!url.is_valid())
81     return false;
82
83   Runtime* runtime = Runtime::Create(runtime_context_, this);
84   render_process_host_ = runtime->GetRenderProcessHost();
85   render_process_host_->AddObserver(this);
86   InitSecurityPolicy();
87   runtime->LoadURL(url);
88
89   NativeAppWindow::CreateParams params;
90   params.net_wm_pid = launch_params.launcher_pid;
91   params.state = GetWindowShowState(launch_params);
92   runtime->AttachWindow(params);
93
94   return true;
95 }
96
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()) {
102       *used = StartURLKey;
103       return url;
104     }
105   }
106
107   if (params.entry_points & LaunchLocalPathKey) {
108     GURL url = GetURLFromRelativePathKey(
109         GetLaunchLocalPathKey(data_->GetPackageType()));
110     if (url.is_valid()) {
111       *used = LaunchLocalPathKey;
112       return url;
113     }
114   }
115
116   if (params.entry_points & URLKey) {
117     GURL url = GetURLFromURLKey();
118     if (url.is_valid()) {
119       *used = URLKey;
120       return url;
121     }
122   }
123
124   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
125   return GURL();
126 }
127
128 ui::WindowShowState Application::GetWindowShowState(
129     const LaunchParams& params) {
130   if (params.force_fullscreen)
131     return ui::SHOW_STATE_FULLSCREEN;
132
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;
140   }
141
142   return ui::SHOW_STATE_DEFAULT;
143 }
144
145 GURL Application::GetURLFromURLKey() {
146   const Manifest* manifest = data_->GetManifest();
147   std::string url_string;
148   if (!manifest->GetString(keys::kURLKey, &url_string))
149     return GURL();
150
151   return GURL(url_string);
152 }
153
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)
160       return GURL();
161
162     base::FileEnumerator iter(data_->Path(), true,
163                               base::FileEnumerator::FILES,
164                               FILE_PATH_LITERAL("index.*"));
165     int priority = arraysize(kDefaultWidgetEntryPage);
166
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] &&
170             i < priority) {
171           entry_page = kDefaultWidgetEntryPage[i];
172           priority = i;
173         }
174       }
175     }
176
177     if (entry_page.empty())
178       return GURL();
179   }
180
181   return data_->GetResourceURL(entry_page);
182 }
183
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));
188 }
189
190 int Application::GetRenderProcessHostID() const {
191   DCHECK(render_process_host_);
192   return render_process_host_->GetID();
193 }
194
195 void Application::OnRuntimeAdded(Runtime* runtime) {
196   DCHECK(runtime);
197   runtimes_.insert(runtime);
198 }
199
200 void Application::OnRuntimeRemoved(Runtime* runtime) {
201   DCHECK(runtime);
202   runtimes_.erase(runtime);
203
204   if (runtimes_.empty()) {
205 #if defined(OS_TIZEN_MOBILE)
206     runtime->CloseRootWindow();
207 #endif
208     base::MessageLoop::current()->PostTask(FROM_HERE,
209         base::Bind(&Application::NotifyTermination,
210                    weak_factory_.GetWeakPtr()));
211     return;
212   }
213 }
214
215 void Application::RenderProcessExited(RenderProcessHost* host,
216                                       base::ProcessHandle,
217                                       base::TerminationStatus,
218                                       int) {
219   DCHECK(render_process_host_ == host);
220   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
221   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
222 }
223
224 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
225   DCHECK(render_process_host_ == host);
226   render_process_host_ = NULL;
227 }
228
229 void Application::NotifyTermination() {
230   CHECK(!render_process_host_);
231   observer_->OnApplicationTerminated(this);
232 }
233
234 bool Application::UseExtension(const std::string& extension_name) const {
235   // TODO(Bai): Tells whether the application contains the specified extension
236   return true;
237 }
238
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))
247     return false;
248
249   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
250   if (permission_list->GetSize() == 0)
251     return false;
252
253   for (base::ListValue::const_iterator iter = permission_list->begin();
254       iter != permission_list->end(); ++iter) {
255     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
256         return false;
257
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))
262       return false;
263
264     base::ListValue* api_list = NULL;
265     if (!dict_val->GetList("apis", &api_list))
266       return false;
267
268     for (base::ListValue::const_iterator api_iter = api_list->begin();
269         api_iter != api_list->end(); ++api_iter) {
270       std::string api;
271       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
272           && (*api_iter)->GetAsString(&api)))
273         return false;
274       // register the permission and api
275       name_perm_map_[api] = permission_name;
276       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
277                  << " [API] " << api;
278     }
279   }
280
281   return true;
282 }
283
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("");
291   return iter->second;
292 }
293
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;
301     return iter->second;
302   }
303   if (type == PERSISTENT_PERMISSION) {
304     return data_->GetPermission(permission_name);
305   }
306   NOTREACHED();
307   return UNDEFINED_STORED_PERM;
308 }
309
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;
315     return true;
316   }
317   if (type == PERSISTENT_PERMISSION)
318     return data_->SetPermission(permission_name, perm);
319
320   NOTREACHED();
321   return false;
322 }
323
324 void Application::InitSecurityPolicy() {
325   if (data_->GetPackageType() != Package::WGT)
326     return;
327
328   const WARPInfo* info = static_cast<WARPInfo*>(
329       data_->GetManifestData(widget_keys::kAccessKey));
330   // FIXME(xinchao): Need to enable WARP mode by default.
331   if (!info)
332     return;
333
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);
339     std::string dest;
340     if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
341         dest.empty())
342       continue;
343     if (dest == "*") {
344       security_mode_enabled_ = false;
345       break;
346     }
347
348     GURL dest_url(dest);
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;
354   }
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));
361   }
362 }
363
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));
371 }
372
373 bool Application::CanRequestURL(const GURL& url) const {
374   if (!security_mode_enabled_)
375     return true;
376
377   // Only WGT package need to check the url request permission.
378   if (data_->GetPackageType() != Package::WGT)
379     return true;
380
381   // Always can request itself resources.
382   if (url.SchemeIs(application::kApplicationScheme) &&
383       url.host() == id())
384     return true;
385
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)
392       return true;
393   }
394   return false;
395 }
396
397 }  // namespace application
398 }  // namespace xwalk