Upstream version 9.38.207.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   "content-security-policy-report-only",
66   "content-security-policy",
67   "content"
68 };
69
70 inline char* ToCharPointer(void* ptr) {
71   return reinterpret_cast<char *>(ptr);
72 }
73
74 inline const char* ToConstCharPointer(const void* ptr) {
75   return reinterpret_cast<const char*>(ptr);
76 }
77
78 base::string16 ToSting16(const xmlChar* string_ptr) {
79   return base::UTF8ToUTF16(std::string(ToConstCharPointer(string_ptr)));
80 }
81
82 base::string16 GetDirText(const base::string16& text, const std::string& dir) {
83   if (dir == kDirLTRKey)
84     return base::i18n::kLeftToRightEmbeddingMark
85            + text
86            + base::i18n::kPopDirectionalFormatting;
87
88   if (dir == kDirRTLKey)
89     return base::i18n::kRightToLeftEmbeddingMark
90            + text
91            + base::i18n::kPopDirectionalFormatting;
92
93   if (dir == kDirLROKey)
94     return base::i18n::kLeftToRightOverride
95            + text
96            + base::i18n::kPopDirectionalFormatting;
97
98   if (dir == kDirRLOKey)
99     return base::i18n::kRightToLeftOverride
100            + text
101            + base::i18n::kPopDirectionalFormatting;
102
103   return text;
104 }
105
106 std::string GetNodeDir(xmlNode* node, const std::string& inherit_dir) {
107   DCHECK(node);
108   std::string dir(inherit_dir);
109
110   xmlAttr* prop = NULL;
111   for (prop = node->properties; prop; prop = prop->next) {
112     if (xmlStrEqual(prop->name, kDirAttributeKey)) {
113       char* prop_value = ToCharPointer(xmlNodeListGetString(
114           node->doc, prop->children, 1));
115       dir = prop_value;
116       xmlFree(prop_value);
117       break;
118     }
119   }
120
121   return dir;
122 }
123
124 base::string16 GetNodeText(xmlNode* root, const std::string& inherit_dir) {
125   DCHECK(root);
126   if (root->type != XML_ELEMENT_NODE)
127     return base::string16();
128
129   std::string current_dir(GetNodeDir(root, inherit_dir));
130   base::string16 text;
131   for (xmlNode* node = root->children; node; node = node->next) {
132     if (node->type == XML_TEXT_NODE || node->type == XML_CDATA_SECTION_NODE) {
133       text = text + base::i18n::StripWrappingBidiControlCharacters(
134                         ToSting16(node->content));
135     } else {
136       text = text + GetNodeText(node, current_dir);
137     }
138   }
139   return GetDirText(text, current_dir);
140 }
141
142 // According to widget specification, this two prop need to support dir.
143 // see detail on http://www.w3.org/TR/widgets/#the-dir-attribute
144 inline bool IsPropSupportDir(xmlNode* root, xmlAttr* prop) {
145   if (xmlStrEqual(root->name, kWidgetNodeKey)
146      && xmlStrEqual(prop->name, kVersionAttributeKey))
147     return true;
148   if (xmlStrEqual(root->name, kNameNodeKey)
149      && xmlStrEqual(prop->name, kShortAttributeKey))
150     return true;
151   return false;
152 }
153
154 // Only this four items need to support span and ignore other element.
155 // Besides xmlNodeListGetString can not support dir prop of span.
156 // See http://www.w3.org/TR/widgets/#the-span-element-and-its-attributes
157 inline bool IsElementSupportSpanAndDir(xmlNode* root) {
158   if (xmlStrEqual(root->name, kNameNodeKey)
159      || xmlStrEqual(root->name, kDescriptionNodeKey)
160      || xmlStrEqual(root->name, kAuthorNodeKey)
161      || xmlStrEqual(root->name, kLicenseNodeKey))
162     return true;
163   return false;
164 }
165
166 bool IsSingletonElement(const std::string& name) {
167   for (int i = 0; i < arraysize(kSingletonElements); ++i)
168     if (kSingletonElements[i] == name)
169 #if defined(OS_TIZEN)
170       // On Tizen platform, need to check namespace of 'content'
171       // element further, a content element with tizen namespace
172       // will replace the one with widget namespace.
173       return name != kContentKey;
174 #else
175       return true;
176 #endif
177   return false;
178 }
179
180 }  // namespace
181
182 namespace xwalk {
183 namespace application {
184
185 FileDeleter::FileDeleter(const base::FilePath& path, bool recursive)
186     : path_(path),
187       recursive_(recursive) {}
188
189 FileDeleter::~FileDeleter() {
190   base::DeleteFile(path_, recursive_);
191 }
192
193 namespace {
194
195 // Load XML node into Dictionary structure.
196 // The keys for the XML node to Dictionary mapping are described below:
197 // XML                                 Dictionary
198 // <e></e>                             "e":{"#text": ""}
199 // <e>textA</e>                        "e":{"#text":"textA"}
200 // <e attr="val">textA</e>             "e":{ "@attr":"val", "#text": "textA"}
201 // <e> <a>textA</a> <b>textB</b> </e>  "e":{
202 //                                       "a":{"#text":"textA"}
203 //                                       "b":{"#text":"textB"}
204 //                                     }
205 // <e> <a>textX</a> <a>textY</a> </e>  "e":{
206 //                                       "a":[ {"#text":"textX"},
207 //                                             {"#text":"textY"}]
208 //                                     }
209 // <e> textX <a>textY</a> </e>         "e":{ "#text":"textX",
210 //                                           "a":{"#text":"textY"}
211 //                                     }
212 //
213 // For elements that are specified under a namespace, the dictionary
214 // will add '@namespace' key for them, e.g.,
215 // XML:
216 // <e xmln="linkA" xmlns:N="LinkB">
217 //   <sub-e1> text1 </sub-e>
218 //   <N:sub-e2 text2 />
219 // </e>
220 // will be saved in Dictionary as,
221 // "e":{
222 //   "#text": "",
223 //   "@namespace": "linkA"
224 //   "sub-e1": {
225 //     "#text": "text1",
226 //     "@namespace": "linkA"
227 //   },
228 //   "sub-e2": {
229 //     "#text":"text2"
230 //     "@namespace": "linkB"
231 //   }
232 // }
233 base::DictionaryValue* LoadXMLNode(
234     xmlNode* root, const std::string& inherit_dir = "") {
235   scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue);
236   if (root->type != XML_ELEMENT_NODE)
237     return NULL;
238
239   std::string current_dir(GetNodeDir(root, inherit_dir));
240
241   xmlAttr* prop = NULL;
242   for (prop = root->properties; prop; prop = prop->next) {
243     xmlChar* value_ptr = xmlNodeListGetString(root->doc, prop->children, 1);
244     base::string16 prop_value(ToSting16(value_ptr));
245     xmlFree(value_ptr);
246
247     if (IsPropSupportDir(root, prop))
248       prop_value = GetDirText(prop_value, current_dir);
249
250     value->SetString(
251         std::string(kAttributePrefix) + ToConstCharPointer(prop->name),
252         prop_value);
253   }
254
255   if (root->ns)
256     value->SetString(kNamespaceKey, ToConstCharPointer(root->ns->href));
257
258   for (xmlNode* node = root->children; node; node = node->next) {
259     std::string sub_node_name(ToConstCharPointer(node->name));
260     base::DictionaryValue* sub_value = LoadXMLNode(node, current_dir);
261     if (!sub_value)
262       continue;
263
264     if (!value->HasKey(sub_node_name)) {
265       value->Set(sub_node_name, sub_value);
266       continue;
267     } else if (IsSingletonElement(sub_node_name)) {
268       continue;
269 #if defined(OS_TIZEN)
270     } else if (sub_node_name == kContentKey) {
271       std::string current_namespace, new_namespace;
272       base::DictionaryValue* current_value;
273       value->GetDictionary(sub_node_name, &current_value);
274
275       current_value->GetString(kNamespaceKey, &current_namespace);
276       sub_value->GetString(kNamespaceKey, &new_namespace);
277       if (current_namespace != new_namespace &&
278           new_namespace == kTizenNamespacePrefix)
279         value->Set(sub_node_name, sub_value);
280       continue;
281 #endif
282     }
283
284     base::Value* temp;
285     value->Get(sub_node_name, &temp);
286     DCHECK(temp);
287
288     if (temp->IsType(base::Value::TYPE_LIST)) {
289       base::ListValue* list;
290       temp->GetAsList(&list);
291       list->Append(sub_value);
292     } else {
293       DCHECK(temp->IsType(base::Value::TYPE_DICTIONARY));
294       base::DictionaryValue* dict;
295       temp->GetAsDictionary(&dict);
296       base::DictionaryValue* prev_value(new base::DictionaryValue());
297       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