Upstream version 11.39.260.0
[platform/framework/web/crosswalk.git] / src / xwalk / application / common / application_file_util.cc
1 // Copyright (c) 2013 The Chromium Authors. 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/common/application_file_util.h"
6
7 #include <algorithm>
8 #include <map>
9 #include <vector>
10
11 #include "base/command_line.h"
12 #include "base/files/file_path.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/file_util.h"
15 #include "base/i18n/rtl.h"
16 #include "base/json/json_file_value_serializer.h"
17 #include "base/logging.h"
18 #include "base/metrics/histogram.h"
19 #include "base/path_service.h"
20 #include "base/strings/string16.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "net/base/escape.h"
25 #include "net/base/file_stream.h"
26 #include "third_party/libxml/src/include/libxml/tree.h"
27 #include "ui/base/l10n/l10n_util.h"
28 #include "xwalk/application/common/application_data.h"
29 #include "xwalk/application/common/application_manifest_constants.h"
30 #include "xwalk/application/common/constants.h"
31 #include "xwalk/application/common/manifest.h"
32 #include "xwalk/application/common/manifest_handler.h"
33
34 #if defined(OS_TIZEN)
35 #include "xwalk/application/common/id_util.h"
36 #endif
37
38 namespace errors = xwalk::application_manifest_errors;
39 namespace keys = xwalk::application_manifest_keys;
40 namespace widget_keys = xwalk::application_widget_keys;
41
42 namespace {
43 const char kAttributePrefix[] = "@";
44 const char kNamespaceKey[] = "@namespace";
45 const char kTextKey[] = "#text";
46
47 const char kContentKey[] = "content";
48
49 const xmlChar kWidgetNodeKey[] = "widget";
50 const xmlChar kNameNodeKey[] = "name";
51 const xmlChar kDescriptionNodeKey[] = "description";
52 const xmlChar kAuthorNodeKey[] = "author";
53 const xmlChar kLicenseNodeKey[] = "license";
54 const xmlChar kVersionAttributeKey[] = "version";
55 const xmlChar kShortAttributeKey[] = "short";
56 const xmlChar kDirAttributeKey[] = "dir";
57
58 const char kDirLTRKey[] = "ltr";
59 const char kDirRTLKey[] = "rtl";
60 const char kDirLROKey[] = "lro";
61 const char kDirRLOKey[] = "rlo";
62
63 const char* kSingletonElements[] = {
64   "allow-navigation",
65   "author",
66   "content-security-policy-report-only",
67   "content-security-policy",
68   "content"
69 };
70
71 inline char* ToCharPointer(void* ptr) {
72   return reinterpret_cast<char *>(ptr);
73 }
74
75 inline const char* ToConstCharPointer(const void* ptr) {
76   return reinterpret_cast<const char*>(ptr);
77 }
78
79 base::string16 ToSting16(const xmlChar* string_ptr) {
80   return base::UTF8ToUTF16(std::string(ToConstCharPointer(string_ptr)));
81 }
82
83 base::string16 GetDirText(const base::string16& text, const std::string& dir) {
84   if (dir == kDirLTRKey)
85     return base::i18n::kLeftToRightEmbeddingMark
86            + text
87            + base::i18n::kPopDirectionalFormatting;
88
89   if (dir == kDirRTLKey)
90     return base::i18n::kRightToLeftEmbeddingMark
91            + text
92            + base::i18n::kPopDirectionalFormatting;
93
94   if (dir == kDirLROKey)
95     return base::i18n::kLeftToRightOverride
96            + text
97            + base::i18n::kPopDirectionalFormatting;
98
99   if (dir == kDirRLOKey)
100     return base::i18n::kRightToLeftOverride
101            + text
102            + base::i18n::kPopDirectionalFormatting;
103
104   return text;
105 }
106
107 std::string GetNodeDir(xmlNode* node, const std::string& inherit_dir) {
108   DCHECK(node);
109   std::string dir(inherit_dir);
110
111   xmlAttr* prop = NULL;
112   for (prop = node->properties; prop; prop = prop->next) {
113     if (xmlStrEqual(prop->name, kDirAttributeKey)) {
114       char* prop_value = ToCharPointer(xmlNodeListGetString(
115           node->doc, prop->children, 1));
116       dir = prop_value;
117       xmlFree(prop_value);
118       break;
119     }
120   }
121
122   return dir;
123 }
124
125 base::string16 GetNodeText(xmlNode* root, const std::string& inherit_dir) {
126   DCHECK(root);
127   if (root->type != XML_ELEMENT_NODE)
128     return base::string16();
129
130   std::string current_dir(GetNodeDir(root, inherit_dir));
131   base::string16 text;
132   for (xmlNode* node = root->children; node; node = node->next) {
133     if (node->type == XML_TEXT_NODE || node->type == XML_CDATA_SECTION_NODE) {
134       text = text + base::i18n::StripWrappingBidiControlCharacters(
135                         ToSting16(node->content));
136     } else {
137       text = text + GetNodeText(node, current_dir);
138     }
139   }
140   return GetDirText(text, current_dir);
141 }
142
143 // According to widget specification, this two prop need to support dir.
144 // see detail on http://www.w3.org/TR/widgets/#the-dir-attribute
145 inline bool IsPropSupportDir(xmlNode* root, xmlAttr* prop) {
146   if (xmlStrEqual(root->name, kWidgetNodeKey)
147      && xmlStrEqual(prop->name, kVersionAttributeKey))
148     return true;
149   if (xmlStrEqual(root->name, kNameNodeKey)
150      && xmlStrEqual(prop->name, kShortAttributeKey))
151     return true;
152   return false;
153 }
154
155 // Only this four items need to support span and ignore other element.
156 // Besides xmlNodeListGetString can not support dir prop of span.
157 // See http://www.w3.org/TR/widgets/#the-span-element-and-its-attributes
158 inline bool IsElementSupportSpanAndDir(xmlNode* root) {
159   if (xmlStrEqual(root->name, kNameNodeKey)
160      || xmlStrEqual(root->name, kDescriptionNodeKey)
161      || xmlStrEqual(root->name, kAuthorNodeKey)
162      || xmlStrEqual(root->name, kLicenseNodeKey))
163     return true;
164   return false;
165 }
166
167 bool IsSingletonElement(const std::string& name) {
168   for (int i = 0; i < arraysize(kSingletonElements); ++i)
169     if (kSingletonElements[i] == name)
170 #if defined(OS_TIZEN)
171       // On Tizen platform, need to check namespace of 'content'
172       // element further, a content element with tizen namespace
173       // will replace the one with widget namespace.
174       return name != kContentKey;
175 #else
176       return true;
177 #endif
178   return false;
179 }
180
181 }  // namespace
182
183 namespace xwalk {
184 namespace application {
185
186 FileDeleter::FileDeleter(const base::FilePath& path, bool recursive)
187     : path_(path),
188       recursive_(recursive) {}
189
190 FileDeleter::~FileDeleter() {
191   base::DeleteFile(path_, recursive_);
192 }
193
194 namespace {
195
196 // Load XML node into Dictionary structure.
197 // The keys for the XML node to Dictionary mapping are described below:
198 // XML                                 Dictionary
199 // <e></e>                             "e":{"#text": ""}
200 // <e>textA</e>                        "e":{"#text":"textA"}
201 // <e attr="val">textA</e>             "e":{ "@attr":"val", "#text": "textA"}
202 // <e> <a>textA</a> <b>textB</b> </e>  "e":{
203 //                                       "a":{"#text":"textA"}
204 //                                       "b":{"#text":"textB"}
205 //                                     }
206 // <e> <a>textX</a> <a>textY</a> </e>  "e":{
207 //                                       "a":[ {"#text":"textX"},
208 //                                             {"#text":"textY"}]
209 //                                     }
210 // <e> textX <a>textY</a> </e>         "e":{ "#text":"textX",
211 //                                           "a":{"#text":"textY"}
212 //                                     }
213 //
214 // For elements that are specified under a namespace, the dictionary
215 // will add '@namespace' key for them, e.g.,
216 // XML:
217 // <e xmln="linkA" xmlns:N="LinkB">
218 //   <sub-e1> text1 </sub-e>
219 //   <N:sub-e2 text2 />
220 // </e>
221 // will be saved in Dictionary as,
222 // "e":{
223 //   "#text": "",
224 //   "@namespace": "linkA"
225 //   "sub-e1": {
226 //     "#text": "text1",
227 //     "@namespace": "linkA"
228 //   },
229 //   "sub-e2": {
230 //     "#text":"text2"
231 //     "@namespace": "linkB"
232 //   }
233 // }
234 base::DictionaryValue* LoadXMLNode(
235     xmlNode* root, const std::string& inherit_dir = "") {
236   scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue);
237   if (root->type != XML_ELEMENT_NODE)
238     return NULL;
239
240   std::string current_dir(GetNodeDir(root, inherit_dir));
241
242   xmlAttr* prop = NULL;
243   for (prop = root->properties; prop; prop = prop->next) {
244     xmlChar* value_ptr = xmlNodeListGetString(root->doc, prop->children, 1);
245     base::string16 prop_value(ToSting16(value_ptr));
246     xmlFree(value_ptr);
247
248     if (IsPropSupportDir(root, prop))
249       prop_value = GetDirText(prop_value, current_dir);
250
251     value->SetString(
252         std::string(kAttributePrefix) + ToConstCharPointer(prop->name),
253         prop_value);
254   }
255
256   if (root->ns)
257     value->SetString(kNamespaceKey, ToConstCharPointer(root->ns->href));
258
259   for (xmlNode* node = root->children; node; node = node->next) {
260     std::string sub_node_name(ToConstCharPointer(node->name));
261     base::DictionaryValue* sub_value = LoadXMLNode(node, current_dir);
262     if (!sub_value)
263       continue;
264
265     if (!value->HasKey(sub_node_name)) {
266       value->Set(sub_node_name, sub_value);
267       continue;
268     } else if (IsSingletonElement(sub_node_name)) {
269       continue;
270 #if defined(OS_TIZEN)
271     } else if (sub_node_name == kContentKey) {
272       std::string current_namespace, new_namespace;
273       base::DictionaryValue* current_value;
274       value->GetDictionary(sub_node_name, &current_value);
275
276       current_value->GetString(kNamespaceKey, &current_namespace);
277       sub_value->GetString(kNamespaceKey, &new_namespace);
278       if (current_namespace != new_namespace &&
279           new_namespace == widget_keys::kTizenNamespacePrefix)
280         value->Set(sub_node_name, sub_value);
281       continue;
282 #endif
283     }
284
285     base::Value* temp;
286     value->Get(sub_node_name, &temp);
287     DCHECK(temp);
288
289     if (temp->IsType(base::Value::TYPE_LIST)) {
290       base::ListValue* list;
291       temp->GetAsList(&list);
292       list->Append(sub_value);
293     } else {
294       DCHECK(temp->IsType(base::Value::TYPE_DICTIONARY));
295       base::DictionaryValue* dict;
296       temp->GetAsDictionary(&dict);
297       base::DictionaryValue* prev_value = dict->DeepCopy();
298
299       base::ListValue* list = new base::ListValue();
300       list->Append(prev_value);
301       list->Append(sub_value);
302       value->Set(sub_node_name, list);
303     }
304   }
305
306   base::string16 text;
307   if (IsElementSupportSpanAndDir(root)) {
308     text = GetNodeText(root, current_dir);
309   } else {
310     xmlChar* text_ptr = xmlNodeListGetString(root->doc, root->children, 1);
311     if (text_ptr) {
312       text = ToSting16(text_ptr);
313       xmlFree(text_ptr);
314     }
315   }
316
317   if (!text.empty())
318     value->SetString(kTextKey, text);
319
320   return value.release();
321 }
322
323 }  // namespace
324
325 template <Manifest::Type>
326 scoped_ptr<Manifest> LoadManifest(
327     const base::FilePath& manifest_path, std::string* error);
328
329 template <>
330 scoped_ptr<Manifest> LoadManifest<Manifest::TYPE_MANIFEST>(
331     const base::FilePath& manifest_path, std::string* error) {
332   JSONFileValueSerializer serializer(manifest_path);
333   scoped_ptr<base::Value> root(serializer.Deserialize(NULL, error));
334   if (!root) {
335     if (error->empty()) {
336       // If |error| is empty, than the file could not be read.
337       // It would be cleaner to have the JSON reader give a specific error
338       // in this case, but other code tests for a file error with
339       // error->empty().  For now, be consistent.
340       *error = base::StringPrintf("%s", errors::kManifestUnreadable);
341     } else {
342       *error = base::StringPrintf("%s  %s",
343           errors::kManifestParseError, error->c_str());
344     }
345     return scoped_ptr<Manifest>();
346   }
347
348   if (!root->IsType(base::Value::TYPE_DICTIONARY)) {
349     *error = base::StringPrintf("%s", errors::kManifestUnreadable);
350     return scoped_ptr<Manifest>();
351   }
352
353   scoped_ptr<base::DictionaryValue> dv = make_scoped_ptr(
354       static_cast<base::DictionaryValue*>(root.release()));
355 #if defined(OS_TIZEN)
356   // Ignore any Tizen application ID, as this is automatically generated.
357   dv->Remove(keys::kTizenAppIdKey, NULL);
358 #endif
359
360   return make_scoped_ptr(new Manifest(dv.Pass(), Manifest::TYPE_MANIFEST));
361 }
362
363 template <>
364 scoped_ptr<Manifest> LoadManifest<Manifest::TYPE_WIDGET>(
365     const base::FilePath& manifest_path,
366     std::string* error) {
367   xmlDoc * doc = NULL;
368   xmlNode* root_node = NULL;
369   doc = xmlReadFile(manifest_path.MaybeAsASCII().c_str(), NULL, 0);
370   if (doc == NULL) {
371     *error = base::StringPrintf("%s", errors::kManifestUnreadable);
372     return scoped_ptr<Manifest>();
373   }
374   root_node = xmlDocGetRootElement(doc);
375   base::DictionaryValue* dv = LoadXMLNode(root_node);
376   scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue);
377   if (dv)
378     result->Set(ToConstCharPointer(root_node->name), dv);
379
380   return make_scoped_ptr(new Manifest(result.Pass(), Manifest::TYPE_WIDGET));
381 }
382
383 scoped_ptr<Manifest> LoadManifest(const base::FilePath& manifest_path,
384     Manifest::Type type, std::string* error) {
385   if (type == Manifest::TYPE_MANIFEST)
386     return LoadManifest<Manifest::TYPE_MANIFEST>(manifest_path, error);
387
388   if (type == Manifest::TYPE_WIDGET)
389     return LoadManifest<Manifest::TYPE_WIDGET>(manifest_path, error);
390
391   *error = base::StringPrintf("%s", errors::kManifestUnreadable);
392   return scoped_ptr<Manifest>();
393 }
394
395 base::FilePath GetManifestPath(
396     const base::FilePath& app_directory, Manifest::Type type) {
397   base::FilePath manifest_path;
398   switch (type) {
399     case Manifest::TYPE_WIDGET:
400       manifest_path = app_directory.Append(kManifestWgtFilename);
401       break;
402     case Manifest::TYPE_MANIFEST:
403       manifest_path = app_directory.Append(kManifestXpkFilename);
404       break;
405     default:
406       NOTREACHED();
407   }
408
409   return manifest_path;
410 }
411
412 scoped_refptr<ApplicationData> LoadApplication(
413     const base::FilePath& app_root, const std::string& app_id,
414     ApplicationData::SourceType source_type, Manifest::Type manifest_type,
415     std::string* error) {
416   base::FilePath manifest_path = GetManifestPath(app_root, manifest_type);
417
418   scoped_ptr<Manifest> manifest = LoadManifest(
419       manifest_path, manifest_type, error);
420   if (!manifest)
421     return NULL;
422
423   return ApplicationData::Create(
424       app_root, app_id, source_type, manifest.Pass(), error);
425 }
426
427 base::FilePath ApplicationURLToRelativeFilePath(const GURL& url) {
428   std::string url_path = url.path();
429   if (url_path.empty() || url_path[0] != '/')
430     return base::FilePath();
431
432   // Drop the leading slashes and convert %-encoded UTF8 to regular UTF8.
433   std::string file_path = net::UnescapeURLComponent(url_path,
434       net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
435   size_t skip = file_path.find_first_not_of("/\\");
436   if (skip != file_path.npos)
437     file_path = file_path.substr(skip);
438
439   base::FilePath path =
440 #if defined(OS_POSIX)
441     base::FilePath(file_path);
442 #elif defined(OS_WIN)
443     base::FilePath(base::UTF8ToWide(file_path));
444 #else
445     base::FilePath();
446     NOTIMPLEMENTED();
447 #endif
448
449   // It's still possible for someone to construct an annoying URL whose path
450   // would still wind up not being considered relative at this point.
451   // For example: app://id/c:////foo.html
452   if (path.IsAbsolute())
453     return base::FilePath();
454
455   return path;
456 }
457
458 }  // namespace application
459 }  // namespace xwalk