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
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());
47 ////////////////////////////////////////////////////////////////////////////////
48 let ioSvc
= Cc
["@mozilla.org/network/io-service;1"].getService(Ci
.nsIIOService
);
50 function uriFromUrl (url
, base
) {
52 if (typeof(base
) === "string") {
53 baseUri
= uriFromUrl(base
);
58 return ioSvc
.newURI(url
, null, baseUri
);
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
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
);
82 chashObj
.initWithString(alg
);
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
);
90 uniconvObj
.charset
= charset
;
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
);
119 doc
.body
.appendChild(frag
);
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
];
140 let res
= new ScriptStorage(nfo
);
141 storageObjects
[nfo
.name
] = 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;
153 debuglog("freeing storage object for '", k
, "'");
161 ////////////////////////////////////////////////////////////////////////////////
162 exports
.createSandbox = function (domWin
, nfo
, url
) {
164 let scres
= nfo
.resources
;
167 // create "unwrapped" sandbox
168 sandbox
= Cu
.Sandbox(domWin
, {
169 sandboxName
: "unwrapped",
170 sameZoneAs
: domWin
, // help GC a little
171 sandboxPrototype
: domWin
/*.wrappedJSObject*/,
174 // alias unsafeWindow for compatibility
175 Cu
.evalInSandbox("const unsafeWindow = window;", sandbox
);
176 //sandbox.isWrapped = !nfo.unwrapped;
178 // create "real" sandbox
179 sandbox
= Cu
.Sandbox(domWin
, {
180 sandboxName
: nfo
.name
,
181 sameZoneAs
: domWin
, // help GC a little
182 sandboxPrototype
: domWin
/*.wrappedJSObject*/,
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];
214 var style
= doc
.createElement("style");
215 style
.textContent
= cssstr
;
216 style
.type
= "text/css";
217 head
.appendChild(style
);
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!");
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!");
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
));
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 () {
263 debuglog("**** NUKING SANDBOX *** [", nfo
.name
, "] : [", url
, "]");
264 Cu
.nukeSandbox(sandbox
);
274 ////////////////////////////////////////////////////////////////////////////////
275 exports
.runInSandbox = function (sandbox
, nfo
) {
276 // eval the code, with anonymous wrappers when/if appropriate
277 function evalLazyWrap (code
, fileName
, dowrap
) {
279 Cu
.evalInSandbox(code
, sandbox
, "ECMAv5", fileName
, 1);
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);
292 // eval the code, with a try/catch to report errors cleanly
293 function evalNoThrow (code
, fileName
, dowrap
) {
296 evalLazyWrap(code
, fileName
);
298 logException("UJS", e
);
309 var dirr
= getUserLibDir();
322 var dirr
= getUserJSDir();
323 dirr
.append(nfo
.name
);
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;
337 if (typeof(fname
) !== "string") throw new Error("string expected");
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
);
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
364 sandbox
.requirelib
= tieto(libObj
, includer
);
365 sandbox
.requireinc
= tieto(incObj
, includer
);
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;
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;
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);
397 logException("XUJS", e
);