1// Copyright (c) 2012 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 "chrome/browser/extensions/convert_user_script.h"
6
7#include <string>
8#include <vector>
9
10#include "base/base64.h"
11#include "base/file_util.h"
12#include "base/files/file_path.h"
13#include "base/files/scoped_temp_dir.h"
14#include "base/json/json_file_value_serializer.h"
15#include "base/path_service.h"
16#include "base/strings/string_util.h"
17#include "base/strings/utf_string_conversions.h"
18#include "chrome/browser/extensions/user_script_master.h"
19#include "chrome/common/chrome_paths.h"
20#include "crypto/sha2.h"
21#include "extensions/common/constants.h"
22#include "extensions/common/extension.h"
23#include "extensions/common/file_util.h"
24#include "extensions/common/manifest_constants.h"
25#include "extensions/common/user_script.h"
26#include "url/gurl.h"
27
28namespace extensions {
29
30namespace keys = manifest_keys;
31namespace values = manifest_values;
32
33scoped_refptr<Extension> ConvertUserScriptToExtension(
34    const base::FilePath& user_script_path, const GURL& original_url,
35    const base::FilePath& extensions_dir, base::string16* error) {
36  std::string content;
37  if (!base::ReadFileToString(user_script_path, &content)) {
38    *error = base::ASCIIToUTF16("Could not read source file.");
39    return NULL;
40  }
41
42  if (!base::IsStringUTF8(content)) {
43    *error = base::ASCIIToUTF16("User script must be UTF8 encoded.");
44    return NULL;
45  }
46
47  UserScript script;
48  if (!UserScriptMaster::ScriptReloader::ParseMetadataHeader(content,
49                                                             &script)) {
50    *error = base::ASCIIToUTF16("Invalid script header.");
51    return NULL;
52  }
53
54  base::FilePath install_temp_dir =
55      file_util::GetInstallTempDir(extensions_dir);
56  if (install_temp_dir.empty()) {
57    *error = base::ASCIIToUTF16(
58        "Could not get path to profile temporary directory.");
59    return NULL;
60  }
61
62  base::ScopedTempDir temp_dir;
63  if (!temp_dir.CreateUniqueTempDirUnderPath(install_temp_dir)) {
64    *error = base::ASCIIToUTF16("Could not create temporary directory.");
65    return NULL;
66  }
67
68  // Create the manifest
69  scoped_ptr<base::DictionaryValue> root(new base::DictionaryValue);
70  std::string script_name;
71  if (!script.name().empty() && !script.name_space().empty())
72    script_name = script.name_space() + "/" + script.name();
73  else
74    script_name = original_url.spec();
75
76  // Create the public key.
77  // User scripts are not signed, but the public key for an extension doubles as
78  // its unique identity, and we need one of those. A user script's unique
79  // identity is its namespace+name, so we hash that to create a public key.
80  // There will be no corresponding private key, which means user scripts cannot
81  // be auto-updated, or claimed in the gallery.
82  char raw[crypto::kSHA256Length] = {0};
83  std::string key;
84  crypto::SHA256HashString(script_name, raw, crypto::kSHA256Length);
85  base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key);
86
87  // The script may not have a name field, but we need one for an extension. If
88  // it is missing, use the filename of the original URL.
89  if (!script.name().empty())
90    root->SetString(keys::kName, script.name());
91  else
92    root->SetString(keys::kName, original_url.ExtractFileName());
93
94  // Not all scripts have a version, but we need one. Default to 1.0 if it is
95  // missing.
96  if (!script.version().empty())
97    root->SetString(keys::kVersion, script.version());
98  else
99    root->SetString(keys::kVersion, "1.0");
100
101  root->SetString(keys::kDescription, script.description());
102  root->SetString(keys::kPublicKey, key);
103  root->SetBoolean(keys::kConvertedFromUserScript, true);
104
105  base::ListValue* js_files = new base::ListValue();
106  js_files->Append(new base::StringValue("script.js"));
107
108  // If the script provides its own match patterns, we use those. Otherwise, we
109  // generate some using the include globs.
110  base::ListValue* matches = new base::ListValue();
111  if (!script.url_patterns().is_empty()) {
112    for (URLPatternSet::const_iterator i = script.url_patterns().begin();
113         i != script.url_patterns().end(); ++i) {
114      matches->Append(new base::StringValue(i->GetAsString()));
115    }
116  } else {
117    // TODO(aa): Derive tighter matches where possible.
118    matches->Append(new base::StringValue("http://*/*"));
119    matches->Append(new base::StringValue("https://*/*"));
120  }
121
122  // Read the exclude matches, if any are present.
123  base::ListValue* exclude_matches = new base::ListValue();
124  if (!script.exclude_url_patterns().is_empty()) {
125    for (URLPatternSet::const_iterator i =
126         script.exclude_url_patterns().begin();
127         i != script.exclude_url_patterns().end(); ++i) {
128      exclude_matches->Append(new base::StringValue(i->GetAsString()));
129    }
130  }
131
132  base::ListValue* includes = new base::ListValue();
133  for (size_t i = 0; i < script.globs().size(); ++i)
134    includes->Append(new base::StringValue(script.globs().at(i)));
135
136  base::ListValue* excludes = new base::ListValue();
137  for (size_t i = 0; i < script.exclude_globs().size(); ++i)
138    excludes->Append(new base::StringValue(script.exclude_globs().at(i)));
139
140  base::DictionaryValue* content_script = new base::DictionaryValue();
141  content_script->Set(keys::kMatches, matches);
142  content_script->Set(keys::kExcludeMatches, exclude_matches);
143  content_script->Set(keys::kIncludeGlobs, includes);
144  content_script->Set(keys::kExcludeGlobs, excludes);
145  content_script->Set(keys::kJs, js_files);
146
147  if (script.run_location() == UserScript::DOCUMENT_START)
148    content_script->SetString(keys::kRunAt, values::kRunAtDocumentStart);
149  else if (script.run_location() == UserScript::DOCUMENT_END)
150    content_script->SetString(keys::kRunAt, values::kRunAtDocumentEnd);
151  else if (script.run_location() == UserScript::DOCUMENT_IDLE)
152    // This is the default, but store it just in case we change that.
153    content_script->SetString(keys::kRunAt, values::kRunAtDocumentIdle);
154
155  base::ListValue* content_scripts = new base::ListValue();
156  content_scripts->Append(content_script);
157
158  root->Set(keys::kContentScripts, content_scripts);
159
160  base::FilePath manifest_path = temp_dir.path().Append(kManifestFilename);
161  JSONFileValueSerializer serializer(manifest_path);
162  if (!serializer.Serialize(*root)) {
163    *error = base::ASCIIToUTF16("Could not write JSON.");
164    return NULL;
165  }
166
167  // Write the script file.
168  if (!base::CopyFile(user_script_path,
169                      temp_dir.path().AppendASCII("script.js"))) {
170    *error = base::ASCIIToUTF16("Could not copy script file.");
171    return NULL;
172  }
173
174  // TODO(rdevlin.cronin): Continue removing std::string errors and replacing
175  // with base::string16
176  std::string utf8_error;
177  scoped_refptr<Extension> extension = Extension::Create(
178      temp_dir.path(),
179      Manifest::INTERNAL,
180      *root,
181      Extension::NO_FLAGS,
182      &utf8_error);
183  *error = base::UTF8ToUTF16(utf8_error);
184  if (!extension.get()) {
185    NOTREACHED() << "Could not init extension " << *error;
186    return NULL;
187  }
188
189  temp_dir.Take();  // The caller takes ownership of the directory.
190  return extension;
191}
192
193}  // namespace extensions
194