19b7acacbe644b1cce1bc8e3276e9f6230bcf120
[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 = dict->DeepCopy();
297
298       base::ListValue* list = new base::ListValue();
299       list->Append(prev_value);
300       list->Append(sub_value);
301       value->Set(sub_node_name, list);
302     }
303   }
304
305   base::string16 text;
306   if (IsElementSupportSpanAndDir(root)) {
307     text = GetNodeText(root, current_dir);
308   } else {
309     xmlChar* text_ptr = xmlNodeListGetString(root->doc, root->children, 1);
310     if (text_ptr) {
311       text = ToSting16(text_ptr);
312       xmlFree(text_ptr);
313     }
314   }
315
316   if (!text.empty())
317     value->SetString(kTextKey, text);
318
319   return value.release();
320 }
321
322 }  // namespace
323
324 template <Manifest::Type>
325 scoped_ptr<Manifest> LoadManifest(
326     const base::FilePath& manifest_path, std::string* error);
327
328 template <>
329 scoped_ptr<Manifest> LoadManifest<Manifest::TYPE_MANIFEST>(
330     const base::FilePath& manifest_path, std::string* error) {
331   JSONFileValueSerializer serializer(manifest_path);
332   scoped_ptr<base::Value> root(serializer.Deserialize(NULL, error));
333   if (!root) {
334     if (error->empty()) {
335       // If |error| is empty, than the file could not be read.
336       // It would be cleaner to have the JSON reader give a specific error
337       // in this case, but other code tests for a file error with
338       // error->empty().  For now, be consistent.
339       *error = base::StringPrintf("%s", errors::kManifestUnreadable);
340     } else {
341       *error = base::StringPrintf("%s  %s",
342           errors::kManifestParseError, error->c_str());
343     }
344     return scoped_ptr<Manifest>();
345   }
346
347   if (!root->IsType(base::Value::TYPE_DICTIONARY)) {
348     *error = base::StringPrintf("%s", errors::kManifestUnreadable);
349     return scoped_ptr<Manifest>();
350   }
351
352   scoped_ptr<base::DictionaryValue> dv = make_scoped_ptr(
353       static_cast<base::DictionaryValue*>(root.release()));
354 #if defined(OS_TIZEN)
355   // Ignore any Tizen application ID, as this is automatically generated.
356   dv->Remove(keys::kTizenAppIdKey, NULL);
357 #endif
358
359   return make_scoped_ptr(new Manifest(dv.Pass(), Manifest::TYPE_MANIFEST));
360 }
361
362 template <>
363 scoped_ptr<Manifest> LoadManifest<Manifest::TYPE_WIDGET>(
364     const base::FilePath& manifest_path,
365     std::string* error) {
366   xmlDoc * doc = NULL;
367   xmlNode* root_node = NULL;
368   doc = xmlReadFile(manifest_path.MaybeAsASCII().c_str(), NULL, 0);
369   if (doc == NULL) {
370     *error = base::StringPrintf("%s", errors::kManifestUnreadable);
371     return scoped_ptr<Manifest>();
372   }
373   root_node = xmlDocGetRootElement(doc);
374   base::DictionaryValue* dv = LoadXMLNode(root_node);
375   scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue);
376   if (dv)
377     result->Set(ToConstCharPointer(root_node->name), dv);
378
379   return make_scoped_ptr(new Manifest(result.Pass(), Manifest::TYPE_WIDGET));
380 }
381
382 scoped_ptr<Manifest> LoadManifest(const base::FilePath& manifest_path,
383     Manifest::Type type, std::string* error) {
384   if (type == Manifest::TYPE_MANIFEST)
385     return LoadManifest<Manifest::TYPE_MANIFEST>(manifest_path, error);
386
387   if (type == Manifest::TYPE_WIDGET)
388     return LoadManifest<Manifest::TYPE_WIDGET>(manifest_path, error);
389
390   *error = base::StringPrintf("%s", errors::kManifestUnreadable);
391   return scoped_ptr<Manifest>();
392 }
393
394 base::FilePath GetManifestPath(
395     const base::FilePath& app_directory, Manifest::Type type) {
396   base::FilePath manifest_path;
397   switch (type) {
398     case Manifest::TYPE_WIDGET:
399       manifest_path = app_directory.Append(kManifestWgtFilename);
400       break;
401     case Manifest::TYPE_MANIFEST:
402       manifest_path = app_directory.Append(kManifestXpkFilename);
403       break;
404     default:
405       NOTREACHED();
406   }
407
408   return manifest_path;
409 }
410
411 scoped_refptr<ApplicationData> LoadApplication(
412     const base::FilePath& app_root, const std::string& app_id,
413     ApplicationData::SourceType source_type, Manifest::Type manifest_type,
414     std::string* error) {
415   base::FilePath manifest_path = GetManifestPath(app_root, manifest_type);
416
417   scoped_ptr<Manifest> manifest = LoadManifest(
418       manifest_path, manifest_type, error);
419   if (!manifest)
420     return NULL;
421
422   return ApplicationData::Create(
423       app_root, app_id, source_type, manifest.Pass(), error);
424 }
425
426 base::FilePath ApplicationURLToRelativeFilePath(const GURL& url) {
427   std::string url_path = url.path();
428   if (url_path.empty() || url_path[0] != '/')
429     return base::FilePath();
430
431   // Drop the leading slashes and convert %-encoded UTF8 to regular UTF8.
432   std::string file_path = net::UnescapeURLComponent(url_path,
433       net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
434   size_t skip = file_path.find_first_not_of("/\\");
435   if (skip != file_path.npos)
436     file_path = file_path.substr(skip);
437
438   base::FilePath path =
439 #if defined(OS_POSIX)
440     base::FilePath(file_path);
441 #elif defined(OS_WIN)
442     base::FilePath(base::UTF8ToWide(file_path));
443 #else
444     base::FilePath();
445     NOTIMPLEMENTED();
446 #endif
447
448   // It's still possible for someone to construct an annoying URL whose path
449   // would still wind up not being considered relative at this point.
450   // For example: app://id/c:////foo.html
451   if (path.IsAbsolute())
452     return base::FilePath();
453
454   return path;
455 }
456
457 }  // namespace application
458 }  // namespace xwalk