some fixes
[guerillascript.git] / main / modules / sbapi / sandbox.js
blob34cf3431a11758ec7654f4532a5a10709ae57980
1 /*
2 * Portions copyright 2004-2007 Aaron Boodman
3 * Copyright 2015 Ketmar Dark <ketmar@ketmar.no-ip.org>
4 * Contributors: See contributors list in install.rdf and CREDITS
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * Note that this license applies only to the Greasemonkey extension source
14 * files, not to the user scripts which it runs. User scripts are licensed
15 * separately by their authors.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
25 * The above copyright notice and this permission notice shall be included in all
26 * copies or substantial portions of the Software.
28 ////////////////////////////////////////////////////////////////////////////////
29 const {GuerillaXmlHttpReqester} = require("sbapi/xmlhttprequest");
30 const {ScriptStorage} = require("sbapi/scriptstorage");
31 const {openTab} = require("sbapi/opentab");
32 const {buildRelFile} = require("scriptcache");
35 ////////////////////////////////////////////////////////////////////////////////
36 function fileReadBinary (fl) {
37 let istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
38 istream.init(fl, -1, -1, false);
39 let bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
40 bstream.setInputStream(istream);
41 let bytes = bstream.readBytes(bstream.available());
42 bstream.close();
43 return bytes;
47 ////////////////////////////////////////////////////////////////////////////////
48 let ioSvc = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
50 function uriFromUrl (url, base) {
51 let baseUri = null;
52 if (typeof(base) === "string") {
53 baseUri = uriFromUrl(base);
54 } else if (base) {
55 baseUri = base;
57 try {
58 return ioSvc.newURI(url, null, baseUri);
59 } catch (e) {
60 return null;
65 const newFileURI = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newFileURI;
68 ////////////////////////////////////////////////////////////////////////////////
69 // string aString: A string of data to be hashed.
70 // string aAlg: optional; the hash algorithm to be used; possible values are: MD2, MD5, SHA1, SHA256, SHA384, and SHA512; defaults to SHA1
71 // string aCharset: optional; the charset used by the passed string; defaults to UTF-8
72 function cryptoHashStr (aString, aAlg, aCharset) {
73 const PR_UINT32_MAX = 0xffffffff; // this tells updateFromStream to read the entire string
75 let str = ""+aString;
76 let alg = (""+(aAlg||"SHA1")).trim().toUpperCase();
77 let charset = (""+(aCharset||"UTF-8")).trim();
79 let chashObj = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
81 try {
82 chashObj.initWithString(alg);
83 } catch (e) {
84 logError("invalid hash algorithm: '"+aAlg+"'");
85 throw new Error("invalid hash algorithm: '"+aAlg+"'");
88 let uniconvObj = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
89 try {
90 uniconvObj.charset = charset;
91 } catch (e) {
92 logError("invalid charset: '"+aCharset+"'");
93 throw new Error("invalid charset: '"+aCharset+"'");
96 if (str) chashObj.updateFromStream(uniconvObj.convertToInputStream(str), PR_UINT32_MAX);
97 let hash = chashObj.finish(false); // hash as raw octets
98 return [("0"+hash.charCodeAt(i).toString(16)).slice(-2) for (i in hash)].join("");
102 ////////////////////////////////////////////////////////////////////////////////
103 function safeHTMLParser (domWin, htmlstr, baseUrl) {
104 //conlog("domWin: "+domWin);
105 //conlog("htmlstr: "+htmlstr);
106 //conlog("baseUrl: "+baseUrl);
107 let doc = domWin.document.implementation.createDocument("", "", domWin.document.implementation.createDocumentType("html", "", ""));
108 doc.appendChild(doc.createElement("html"));
109 doc.documentElement.appendChild(doc.createElement("body"));
111 let baseUri = null, frag;
112 if (typeof(baseUrl) !== "undefined") baseUri = uriFromUrl(baseUrl);
114 let pu = Cc["@mozilla.org/parserutils;1"].createInstance(Ci.nsIParserUtils);
115 if (!pu) { logError("FUCKED!"); return null; }
117 frag = pu.parseFragment(htmlstr, 0, false, baseUri, doc.body);
118 doc.adoptNode(frag);
119 doc.body.appendChild(frag);
120 return doc;
124 ////////////////////////////////////////////////////////////////////////////////
125 function genUUID () {
126 let uuidgen = Cc["@mozilla.org/uuid-generator;1"].createInstance(Ci.nsIUUIDGenerator);
127 if (!uuidgen) throw new Error("no UUID generator available!");
128 return uuidgen.generateUUID().toString();
132 ////////////////////////////////////////////////////////////////////////////////
133 let storageObjects = {};
136 function getStorageObject (nfo) {
137 if (nfo.name in storageObjects) {
138 return storageObjects[nfo.name];
139 } else {
140 let res = new ScriptStorage(nfo);
141 storageObjects[nfo.name] = res;
142 return res;
147 exports.closeStorageObjects = function () {
148 for (let k in storageObjects) {
149 if (typeof(k) != "string") continue;
150 let dbo = storageObjects[k];
151 //if (typeof(dbo) != "object") continue;
152 if (dbo.opened) {
153 debuglog("freeing storage object for '", k, "'");
154 dbo.close();
157 storageObjects = {};
161 ////////////////////////////////////////////////////////////////////////////////
162 exports.createSandbox = function (domWin, nfo, url) {
163 let sandbox;
164 let scres = nfo.resources;
166 if (nfo.unwrapped) {
167 // create "unwrapped" sandbox
168 sandbox = Cu.Sandbox(domWin, {
169 sandboxName: "unwrapped",
170 sameZoneAs: domWin, // help GC a little
171 sandboxPrototype: domWin/*.wrappedJSObject*/,
172 wantXrays: false,
174 // alias unsafeWindow for compatibility
175 Cu.evalInSandbox("const unsafeWindow = window;", sandbox);
176 //sandbox.isWrapped = !nfo.unwrapped;
177 } else {
178 // create "real" sandbox
179 sandbox = Cu.Sandbox(domWin, {
180 sandboxName: nfo.name,
181 sameZoneAs: domWin, // help GC a little
182 sandboxPrototype: domWin/*.wrappedJSObject*/,
183 wantXrays: true,
186 //sandbox.isWrapped = !nfo.unwrapped;
187 // no need for the "bugfix" from GM, as Pale Moon doesn't need it
188 //!sandbox.unsafeWindow = domWin.wrappedJSObject;
189 // alas, Tycho inherited this bug from the new Ff, so reapply it
190 var unsafeWindowGetter = new sandbox.Function("return window.wrappedJSObject||window;");
191 Object.defineProperty(sandbox, "unsafeWindow", {get: unsafeWindowGetter});
192 // functions for interaction with unsafeWindow; see: http://goo.gl/C8Au16
193 sandbox.createObjectIn = Cu.createObjectIn;
194 sandbox.cloneInto = Cu.cloneInto;
195 sandbox.exportFunction = Cu.exportFunction;
197 sandbox.GM_generateUUID = tieto(null, genUUID);
198 sandbox.GM_cryptoHash = tieto(null, cryptoHashStr);
200 //Object.defineProperty(sandbox, "GM_safeHTMLParser", {get: function () tieto(null, safeHTMLParser, domWin)});
201 sandbox.GM_safeHTMLParser = tieto(null, safeHTMLParser, domWin);
203 let scriptStorage = getStorageObject(nfo);
204 sandbox.GM_getValue = tieto(scriptStorage, "getValue");
205 sandbox.GM_setValue = tieto(scriptStorage, "setValue");
206 sandbox.GM_deleteValue = tieto(scriptStorage, "deleteValue");
207 sandbox.GM_listValues = tieto(scriptStorage, "listValues");
209 sandbox.GM_xmlhttpRequest = tieto(new GuerillaXmlHttpReqester(domWin, url, sandbox), "contentStartRequest");
211 sandbox.GM_addStyle = tieto(null, function (doc, cssstr) {
212 var head = doc.getElementsByTagName("head")[0];
213 if (head) {
214 var style = doc.createElement("style");
215 style.textContent = cssstr;
216 style.type = "text/css";
217 head.appendChild(style);
218 return style;
220 return null;
221 }, domWin.document);
223 sandbox.GM_openInTab = tieto(null, openTab, domWin);
225 sandbox.GM_getResourceText = tieto(null, function (name) {
226 if (typeof(name) === "undefined") throw new Error("GM_getResourceText(): no name given!");
227 name = ""+name;
228 let rsrc = scres[name];
229 if (!rsrc) throw new Error("GM_getResourceText(): no resource found: '"+name+"'");
230 return fileReadText(rsrc.file);
233 sandbox.GM_getResourceURL = tieto(null, function (name) {
234 //logError("GM_getResourceURL(): stub!");
235 //throw new Error("GM_getResourceURL() not implemented");
236 if (typeof(name) === "undefined") throw new Error("GM_getResourceText(): no name given!");
237 name = ""+name;
238 let rsrc = scres[name];
239 if (!rsrc) throw new Error("GM_getResourceText(): no resource found: '"+name+"'");
240 let rawdata = fileReadBinary(rsrc.file);
241 return "data:"+rsrc.contenttype+";base64,"+encodeURIComponent(btoa(rawdata));
244 // stubs
245 sandbox.GM_registerMenuCommand = tieto(null, function () { logError("GM_registerMenuCommand(): stub!"); });
246 sandbox.GM_setClipboard = tieto(null, function () { logError("GM_setClipboard(): stub!"); });
249 // provide log functions for both wrapped and unwrapped scripts
250 if (!nfo.unwrapped || nfo.wantlog) {
251 sandbox.conlog = tieto(null, conlog);
252 sandbox.logError = tieto(null, logError);
253 if (!nfo.unwrapped) sandbox.GM_log = tieto(null, conlog);
256 Object.defineProperty(sandbox, "GM_info", {
257 get: tieto(null, function () { logError("GM_info(): stub!"); return {}; }),
260 // nuke sandbox when this window unloaded
261 domWin.addEventListener("unload", function () {
262 if (sandbox) {
263 debuglog("**** NUKING SANDBOX *** [", nfo.name, "] : [", url, "]");
264 Cu.nukeSandbox(sandbox);
265 sandbox = null;
267 }, true);
270 return sandbox;
274 ////////////////////////////////////////////////////////////////////////////////
275 exports.runInSandbox = function (sandbox, nfo) {
276 // eval the code, with anonymous wrappers when/if appropriate
277 function evalLazyWrap (code, fileName, dowrap) {
278 try {
279 Cu.evalInSandbox(code, sandbox, "ECMAv5", fileName, 1);
280 } catch (e) {
281 if (dowrap && ("return not in function" == e.message)) {
282 // we never anon wrap unless forced to by a "return not in a function" error
283 logError("please, do not use `return` in top-level code in "+fileName+":"+e.lineNumber);
284 Cu.evalInSandbox("(function(){ "+code+"\n})()", sandbox, "ECMAv5", fileName, 1);
285 } else {
286 // otherwise raise
287 throw e;
292 // eval the code, with a try/catch to report errors cleanly
293 function evalNoThrow (code, fileName, dowrap) {
294 dowrap = !!dowrap;
295 try {
296 evalLazyWrap(code, fileName);
297 } catch (e) {
298 logException("UJS", e);
299 return false;
301 return true;
304 let libObj = {
305 _dir: null,
306 flist: {},
307 get dir () {
308 if (!this._dir) {
309 var dirr = getUserLibDir();
310 this._dir = dirr;
311 return dirr;
313 return this._dir;
317 let incObj = {
318 _dir: null,
319 flist: {},
320 get dir () {
321 if (!this._dir) {
322 var dirr = getUserJSDir();
323 dirr.append(nfo.name);
324 this._dir = dirr;
325 return dirr;
327 return this._dir;
331 let includer = function (fname) {
332 //debuglog("includer: ", JSON.stringify(fname));
333 if (typeof(fname) === "object") {
334 if (!("length" in fname)) throw new Error("string expected");
335 if (fname.length == 0) return;
336 } else {
337 if (typeof(fname) !== "string") throw new Error("string expected");
338 fname = [fname];
340 for (let jsfn of fname) {
341 if (jsfn === undefined || jsfn === null) continue;
342 if (typeof(jsfn) !== "string") throw new Error("string expected");
343 if (jsfn.length == 0) continue;
344 if (!(/\.js$/.test(jsfn))) jsfn += ".js";
345 let fl = buildRelFile(this.dir, jsfn);
346 //debuglog("loading ", fl.path);
347 if (!fl || !fl.exists() || fl.isDirectory() || !fl.isReadable()) {
348 throw new Error("can't import file: "+jsfn);
350 let path = fl.path;
351 let rq = this.flist[path];
352 if (rq !== undefined) {
353 if (rq === false) return; // nothing to do
354 throw new Error("circular import in file: "+jsfn);
356 this.flist[path] = true; // in progress
357 let text = fileReadText(fl);
358 evalLazyWrap(text, newFileURI(fl).spec, false);
359 this.flist[path] = false; // done
363 try {
364 sandbox.requirelib = tieto(libObj, includer);
365 sandbox.requireinc = tieto(incObj, includer);
367 // eval libraries
368 for (let fl of nfo.libs) {
369 if (!fl.exists() || fl.isDirectory() || !fl.isReadable()) return;
370 if (fl.path in reqLibs) continue; // already required
371 libObj.flist[fl.path] = true;
372 let text = fileReadText(fl);
373 let url = newFileURI(fl).spec;
374 if (!evalNoThrow(text, url)) return;
375 libObj.flist[fl.path] = false;
378 // eval includes
379 for (let fl of nfo.incs) {
380 if (!fl.exists() || fl.isDirectory() || !fl.isReadable()) return;
381 if (fl.path in reqFiles) continue; // already required
382 incObj.flist[fl.path] = true;
383 let text = fileReadText(fl);
384 let url = newFileURI(fl).spec;
385 if (!evalNoThrow(text, url)) return;
386 incObj.flist[fl.path] = false;
389 // eval main script
391 if (!nfo.file.exists() || nfo.file.isDirectory() || !nfo.file.isReadable()) return;
392 let text = fileReadText(nfo.file);
393 let url = newFileURI(nfo.file).spec;
394 evalNoThrow(text, url, true);
396 } catch (e) {
397 logException("XUJS", e);