a1023f89b399872dc86ee520c9655a4a572d5527
[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_event_manager.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/main_document_handler.h"
25 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
26 #include "xwalk/application/common/event_names.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"
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 class FinishEventObserver : public EventObserver {
50  public:
51   FinishEventObserver(
52       ApplicationEventManager* event_manager,
53       Application* application)
54       : EventObserver(event_manager),
55         application_(application) {
56   }
57
58   virtual void Observe(const std::string& app_id,
59                        scoped_refptr<Event> event) OVERRIDE {
60     DCHECK(xwalk::application::kOnJavaScriptEventAck == event->name());
61     std::string ack_event_name;
62     event->args()->GetString(0, &ack_event_name);
63     if (ack_event_name == xwalk::application::kOnSuspend)
64       application_->CloseMainDocument();
65   }
66
67  private:
68   Application* application_;
69 };
70
71 Application::Application(
72     scoped_refptr<ApplicationData> data,
73     RuntimeContext* runtime_context,
74     Observer* observer)
75     : main_runtime_(NULL),
76       application_data_(data),
77       is_security_mode_(false),
78       runtime_context_(runtime_context),
79       observer_(observer),
80       entry_point_used_(Default),
81       termination_mode_used_(Normal),
82       weak_factory_(this) {
83   DCHECK(runtime_context_);
84   DCHECK(application_data_);
85   DCHECK(observer_);
86 }
87
88 Application::~Application() {
89   Terminate(Immediate);
90 }
91
92 bool Application::Launch(const LaunchParams& launch_params) {
93   if (!runtimes_.empty()) {
94     LOG(ERROR) << "Attempt to launch app: " << id()
95                << " that was already launched.";
96     return false;
97   }
98
99   GURL url = GetStartURL(launch_params, &entry_point_used_);
100   if (!url.is_valid())
101     return false;
102
103   main_runtime_ = Runtime::Create(runtime_context_, this);
104   InitSecurityPolicy();
105   main_runtime_->LoadURL(url);
106   if (entry_point_used_ != AppMainKey) {
107     NativeAppWindow::CreateParams params;
108     params.net_wm_pid = launch_params.launcher_pid;
109     params.state = GetWindowShowState(launch_params);
110     main_runtime_->AttachWindow(params);
111   }
112
113   return true;
114 }
115
116 GURL Application::GetStartURL(const LaunchParams& params,
117                                   LaunchEntryPoint* used) {
118   if (params.entry_points & StartURLKey) {
119     GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
120     if (url.is_valid()) {
121       *used = StartURLKey;
122       return url;
123     }
124   }
125
126   if (params.entry_points & AppMainKey) {
127     GURL url = GetURLFromAppMainKey();
128     if (url.is_valid()) {
129       *used = AppMainKey;
130       return url;
131     }
132   }
133
134   if (params.entry_points & LaunchLocalPathKey) {
135     GURL url = GetURLFromRelativePathKey(
136         GetLaunchLocalPathKey(application_data_->GetPackageType()));
137     if (url.is_valid()) {
138       *used = LaunchLocalPathKey;
139       return url;
140     }
141   }
142
143   if (params.entry_points & URLKey) {
144     GURL url = GetURLFromURLKey();
145     if (url.is_valid()) {
146       *used = URLKey;
147       return url;
148     }
149   }
150
151   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
152   return GURL();
153 }
154
155 GURL Application::GetURLFromAppMainKey() {
156   MainDocumentInfo* main_info = ToMainDocumentInfo(
157     application_data_->GetManifestData(keys::kAppMainKey));
158   if (!main_info)
159     return GURL();
160
161   DCHECK(application_data_->HasMainDocument());
162   return main_info->GetMainURL();
163 }
164
165 ui::WindowShowState Application::GetWindowShowState(
166     const LaunchParams& params) {
167   if (params.force_fullscreen)
168     return ui::SHOW_STATE_FULLSCREEN;
169
170   const Manifest* manifest = application_data_->GetManifest();
171   std::string display_string;
172   if (manifest->GetString(keys::kDisplay, &display_string)) {
173     // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
174     // values are supported.
175     if (display_string.find("fullscreen") != std::string::npos)
176       return ui::SHOW_STATE_FULLSCREEN;
177   }
178
179   return ui::SHOW_STATE_DEFAULT;
180 }
181
182 GURL Application::GetURLFromURLKey() {
183   const Manifest* manifest = application_data_->GetManifest();
184   std::string url_string;
185   if (!manifest->GetString(keys::kURLKey, &url_string))
186     return GURL();
187
188   return GURL(url_string);
189 }
190
191 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
192   const Manifest* manifest = application_data_->GetManifest();
193   std::string entry_page;
194   if (!manifest->GetString(key, &entry_page)
195       || entry_page.empty()) {
196     if (application_data_->GetPackageType() == Manifest::TYPE_XPK)
197       return GURL();
198
199     base::FileEnumerator iter(application_data_->Path(), true,
200                               base::FileEnumerator::FILES,
201                               FILE_PATH_LITERAL("index.*"));
202     int priority = arraysize(kDefaultWidgetEntryPage);
203
204     for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
205       for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
206         if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
207             i < priority) {
208           entry_page = kDefaultWidgetEntryPage[i];
209           priority = i;
210         }
211       }
212     }
213
214     if (entry_page.empty())
215       return GURL();
216   }
217
218   return application_data_->GetResourceURL(entry_page);
219 }
220
221 void Application::Terminate(TerminationMode mode) {
222   termination_mode_used_ = mode;
223   if (IsTerminating()) {
224     LOG(WARNING) << "Attempt to Terminate app: " << id()
225                  << ", which is already in the process of being terminated.";
226     if (mode == Immediate)
227       CloseMainDocument();
228
229     return;
230   }
231
232   std::set<Runtime*> to_be_closed(runtimes_);
233   if (HasMainDocument() && to_be_closed.size() > 1) {
234     // The main document runtime is closed separately
235     // (needs some extra logic) in Application::OnRuntimeRemoved.
236     to_be_closed.erase(main_runtime_);
237   }
238
239   std::for_each(to_be_closed.begin(), to_be_closed.end(),
240                 std::mem_fun(&Runtime::Close));
241 }
242
243 Runtime* Application::GetMainDocumentRuntime() const {
244   return HasMainDocument() ? main_runtime_ : NULL;
245 }
246
247 int Application::GetRenderProcessHostID() const {
248   DCHECK(main_runtime_);
249   return main_runtime_->web_contents()->
250           GetRenderProcessHost()->GetID();
251 }
252
253 bool Application::HasMainDocument() const {
254   return entry_point_used_ == AppMainKey;
255 }
256
257 void Application::OnRuntimeAdded(Runtime* runtime) {
258   DCHECK(runtime);
259   runtimes_.insert(runtime);
260 }
261
262 void Application::OnRuntimeRemoved(Runtime* runtime) {
263   DCHECK(runtime);
264   runtimes_.erase(runtime);
265
266   if (runtimes_.empty()) {
267 #if defined(OS_TIZEN_MOBILE)
268     runtime->CloseRootWindow();
269 #endif
270     base::MessageLoop::current()->PostTask(FROM_HERE,
271         base::Bind(&Application::NotifyTermination,
272                    weak_factory_.GetWeakPtr()));
273     return;
274   }
275
276   if (runtimes_.size() == 1 && HasMainDocument() &&
277       ContainsKey(runtimes_, main_runtime_)) {
278     ApplicationSystem* system = XWalkRunner::GetInstance()->app_system();
279     ApplicationEventManager* event_manager = system->event_manager();
280
281     // If onSuspend is not registered in main document,
282     // we close the main document immediately.
283     if (!IsOnSuspendHandlerRegistered() ||
284         termination_mode_used_ == Immediate) {
285       CloseMainDocument();
286       return;
287     }
288
289     DCHECK(!finish_observer_);
290     finish_observer_.reset(
291         new FinishEventObserver(event_manager, this));
292     event_manager->AttachObserver(
293         application_data_->ID(), kOnJavaScriptEventAck,
294         finish_observer_.get());
295
296     scoped_ptr<base::ListValue> event_args(new base::ListValue);
297     scoped_refptr<Event> event = Event::CreateEvent(
298         xwalk::application::kOnSuspend, event_args.Pass());
299     event_manager->SendEvent(application_data_->ID(), event);
300   }
301 }
302
303 void Application::CloseMainDocument() {
304   DCHECK(main_runtime_);
305
306   finish_observer_.reset();
307   main_runtime_->Close();
308   main_runtime_ = NULL;
309 }
310
311 void Application::NotifyTermination() {
312   observer_->OnApplicationTerminated(this);
313 }
314
315 bool Application::IsOnSuspendHandlerRegistered() const {
316   const std::set<std::string>& events = data()->GetEvents();
317   if (events.find(kOnSuspend) == events.end())
318     return false;
319
320   return true;
321 }
322
323 bool Application::UseExtension(const std::string& extension_name) const {
324   // TODO(Bai): Tells whether the application contains the specified extension
325   return true;
326 }
327
328 bool Application::RegisterPermissions(const std::string& extension_name,
329                                       const std::string& perm_table) {
330   // TODO(Bai): Parse the permission table and fill in the name_perm_map_
331   // The perm_table format is a simple JSON string, like
332   // [{"permission_name":"echo","apis":["add","remove","get"]}]
333   scoped_ptr<base::Value> root;
334   root.reset(base::JSONReader().ReadToValue(perm_table));
335   if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
336     return false;
337
338   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
339   if (permission_list->GetSize() == 0)
340     return false;
341
342   for (base::ListValue::const_iterator iter = permission_list->begin();
343       iter != permission_list->end(); ++iter) {
344     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
345         return false;
346
347     base::DictionaryValue* dict_val =
348         static_cast<base::DictionaryValue*>(*iter);
349     std::string permission_name;
350     if (!dict_val->GetString("permission_name", &permission_name))
351       return false;
352
353     base::ListValue* api_list = NULL;
354     if (!dict_val->GetList("apis", &api_list))
355       return false;
356
357     for (base::ListValue::const_iterator api_iter = api_list->begin();
358         api_iter != api_list->end(); ++api_iter) {
359       std::string api;
360       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
361           && (*api_iter)->GetAsString(&api)))
362         return false;
363       // register the permission and api
364       name_perm_map_[api] = permission_name;
365       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
366                  << " [API] " << api;
367     }
368   }
369
370   return true;
371 }
372
373 std::string Application::GetRegisteredPermissionName(
374     const std::string& extension_name,
375     const std::string& api_name) const {
376   std::map<std::string, std::string>::const_iterator iter =
377       name_perm_map_.find(api_name);
378   if (iter == name_perm_map_.end())
379     return std::string("");
380   return iter->second;
381 }
382
383 StoredPermission Application::GetPermission(PermissionType type,
384                                std::string& permission_name) const {
385   if (type == SESSION_PERMISSION) {
386     StoredPermissionMap::const_iterator iter =
387         permission_map_.find(permission_name);
388     if (iter == permission_map_.end())
389       return UNDEFINED_STORED_PERM;
390     return iter->second;
391   }
392   if (type == PERSISTENT_PERMISSION) {
393     return application_data_->GetPermission(permission_name);
394   }
395   NOTREACHED();
396   return UNDEFINED_STORED_PERM;
397 }
398
399 bool Application::SetPermission(PermissionType type,
400                                 const std::string& permission_name,
401                                 StoredPermission perm) {
402   if (type == SESSION_PERMISSION) {
403     permission_map_[permission_name] = perm;
404     return true;
405   }
406   if (type == PERSISTENT_PERMISSION)
407     return application_data_->SetPermission(permission_name, perm);
408
409   NOTREACHED();
410   return false;
411 }
412
413 void Application::InitSecurityPolicy() {
414   if (application_data_->GetPackageType() != Manifest::TYPE_WGT)
415     return;
416
417   const WARPInfo* info = static_cast<WARPInfo*>(
418       application_data_->GetManifestData(widget_keys::kAccessKey));
419   // FIXME(xinchao): Need to enable WARP mode by default.
420   if (!info)
421     return;
422
423   const base::ListValue* whitelist = info->GetWARP();
424   for (base::ListValue::const_iterator it = whitelist->begin();
425        it != whitelist->end(); ++it) {
426     base::DictionaryValue* value = NULL;
427     (*it)->GetAsDictionary(&value);
428     std::string dest;
429     if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
430         dest.empty())
431       continue;
432     if (dest == "*") {
433       is_security_mode_ = false;
434       break;
435     }
436
437     GURL dest_url(dest);
438     // The default subdomains attrubute should be "false".
439     std::string subdomains = "false";
440     value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
441     AddSecurityPolicy(dest_url, (subdomains == "true"));
442     is_security_mode_ = true;
443   }
444   if (is_security_mode_)
445     main_runtime_->GetRenderProcessHost()->Send(
446         new ViewMsg_EnableSecurityMode(
447             ApplicationData::GetBaseURLFromApplicationId(id()),
448             SecurityPolicy::WARP));
449 }
450
451 void Application::AddSecurityPolicy(const GURL& url, bool subdomains) {
452   GURL app_url = application_data_->URL();
453   main_runtime_->GetRenderProcessHost()->Send(
454       new ViewMsg_SetAccessWhiteList(
455           app_url, url, subdomains));
456   security_policy_.push_back(new SecurityPolicy(url, subdomains));
457 }
458
459 bool Application::CanRequestURL(const GURL& url) const {
460   if (!is_security_mode_)
461     return true;
462
463   // Only WGT package need to check the url request permission.
464   if (application_data_->GetPackageType() != Manifest::TYPE_WGT)
465     return true;
466
467   // Always can request itself resources.
468   if (url.SchemeIs(application::kApplicationScheme) &&
469       url.host() == id())
470     return true;
471
472   for (unsigned i = 0; i < security_policy_.size(); ++i) {
473     const GURL& policy = security_policy_[i]->url();
474     bool subdomains = security_policy_[i]->subdomains();
475     bool is_host_matched = subdomains ?
476         url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
477     if (url.scheme() == policy.scheme() && is_host_matched)
478       return true;
479   }
480   return false;
481 }
482
483 }  // namespace application
484 }  // namespace xwalk