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 let {GuerillaXmlHttpReqester
} = require("sbapi/xmlhttprequest");
30 let {ScriptStorage
} = require("sbapi/scriptstorage");
31 let {openTab
} = require("sbapi/opentab");
34 ////////////////////////////////////////////////////////////////////////////////
35 function fileReadBinary (fl
) {
36 let istream
= Cc
["@mozilla.org/network/file-input-stream;1"].createInstance(Ci
.nsIFileInputStream
);
37 istream
.init(fl
, -1, -1, false);
38 let bstream
= Cc
["@mozilla.org/binaryinputstream;1"].createInstance(Ci
.nsIBinaryInputStream
);
39 bstream
.setInputStream(istream
);
40 let bytes
= bstream
.readBytes(bstream
.available());
46 ////////////////////////////////////////////////////////////////////////////////
47 let ioSvc
= Cc
["@mozilla.org/network/io-service;1"].getService(Ci
.nsIIOService
);
49 function uriFromUrl (url
, base
) {
51 if (typeof(base
) === "string") {
52 baseUri
= uriFromUrl(base
);
57 return ioSvc
.newURI(url
, null, baseUri
);
64 ////////////////////////////////////////////////////////////////////////////////
65 // string aString: A string of data to be hashed.
66 // string aAlg: optional; the hash algorithm to be used; possible values are: MD2, MD5, SHA1, SHA256, SHA384, and SHA512; defaults to SHA1
67 // string aCharset: optional; the charset used by the passed string; defaults to UTF-8
68 function cryptoHashStr (aString
, aAlg
, aCharset
) {
69 const PR_UINT32_MAX
= 0xffffffff; // this tells updateFromStream to read the entire string
72 let alg
= (""+(aAlg
||"SHA1")).trim().toUpperCase();
73 let charset
= (""+(aCharset
||"UTF-8")).trim();
75 let chashObj
= Cc
["@mozilla.org/security/hash;1"].createInstance(Ci
.nsICryptoHash
);
78 chashObj
.initWithString(alg
);
80 logError("invalid hash algorithm: '"+aAlg
+"'");
81 throw new Error("invalid hash algorithm: '"+aAlg
+"'");
84 let uniconvObj
= Cc
["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci
.nsIScriptableUnicodeConverter
);
86 uniconvObj
.charset
= charset
;
88 logError("invalid charset: '"+aCharset
+"'");
89 throw new Error("invalid charset: '"+aCharset
+"'");
92 if (str
) chashObj
.updateFromStream(uniconvObj
.convertToInputStream(str
), PR_UINT32_MAX
);
93 let hash
= chashObj
.finish(false); // hash as raw octets
94 return [("0"+hash
.charCodeAt(i
).toString(16)).slice(-2) for (i
in hash
)].join("");
98 ////////////////////////////////////////////////////////////////////////////////
99 function safeHTMLParser (domWin
, htmlstr
, baseUrl
) {
100 //conlog("domWin: "+domWin);
101 //conlog("htmlstr: "+htmlstr);
102 //conlog("baseUrl: "+baseUrl);
103 let doc
= domWin
.document
.implementation
.createDocument("", "", domWin
.document
.implementation
.createDocumentType("html", "", ""));
104 doc
.appendChild(doc
.createElement("html"));
105 doc
.documentElement
.appendChild(doc
.createElement("body"));
107 let baseUri
= null, frag
;
108 if (typeof(baseUrl
) !== "undefined") baseUri
= uriFromUrl(baseUrl
);
110 let pu
= Cc
["@mozilla.org/parserutils;1"].createInstance(Ci
.nsIParserUtils
);
111 if (!pu
) { logError("FUCKED!"); return null; }
113 frag
= pu
.parseFragment(htmlstr
, 0, false, baseUri
, doc
.body
);
115 doc
.body
.appendChild(frag
);
120 ////////////////////////////////////////////////////////////////////////////////
121 function genUUID () {
122 let uuidgen
= Cc
["@mozilla.org/uuid-generator;1"].createInstance(Ci
.nsIUUIDGenerator
);
123 if (!uuidgen
) throw new Error("no UUID generator available!");
124 return uuidgen
.generateUUID().toString();
128 ////////////////////////////////////////////////////////////////////////////////
129 let storageObjects
= {};
132 function getStorageObject (nfo
) {
133 if (nfo
.name
in storageObjects
) {
134 return storageObjects
[nfo
.name
];
136 let res
= new ScriptStorage(nfo
);
137 storageObjects
[nfo
.name
] = res
;
143 exports
.closeStorageObjects = function () {
144 for (let k
in storageObjects
) {
145 if (typeof(k
) != "string") continue;
146 let dbo
= storageObjects
[k
];
147 //if (typeof(dbo) != "object") continue;
149 debuglog("freeing storage object for '", k
, "'");
157 ////////////////////////////////////////////////////////////////////////////////
158 exports
.createSandbox = function (domWin
, nfo
, url
) {
160 let scres
= nfo
.resources
;
163 // create "unwrapped" sandbox
164 sandbox
= Cu
.Sandbox(domWin
, {
165 sandboxName
: "unwrapped",
166 sandboxPrototype
: domWin
/*.wrappedJSObject*/,
169 // alias unsafeWindow for compatibility
170 Cu
.evalInSandbox("const unsafeWindow = window;", sandbox
);
172 // create "real" sandbox
173 sandbox
= Cu
.Sandbox(domWin
, {
174 sandboxName
: nfo
.name
,
175 sandboxPrototype
: domWin
/*.wrappedJSObject*/,
179 // Note that because waivers aren't propagated between origins, we need the
180 // unsafeWindow getter to live in the sandbox. See http://bugzil.la/1043958
181 let unsafeWindowGetter
= new sandbox
.Function("return (window.wrappedJSObject||window);");
182 Object
.defineProperty(sandbox
, "unsafeWindow", {get: unsafeWindowGetter
});
184 sandbox
.GM_generateUUID
= tieto(null, genUUID
);
185 sandbox
.GM_cryptoHash
= tieto(null, cryptoHashStr
);
187 //Object.defineProperty(sandbox, "GM_safeHTMLParser", {get: function () tieto(null, safeHTMLParser, domWin)});
188 sandbox
.GM_safeHTMLParser
= tieto(null, safeHTMLParser
, domWin
);
190 let scriptStorage
= getStorageObject(nfo
);
191 sandbox
.GM_getValue
= tieto(scriptStorage
, "getValue");
192 sandbox
.GM_setValue
= tieto(scriptStorage
, "setValue");
193 sandbox
.GM_deleteValue
= tieto(scriptStorage
, "deleteValue");
194 sandbox
.GM_listValues
= tieto(scriptStorage
, "listValues");
196 sandbox
.GM_xmlhttpRequest
= tieto(new GuerillaXmlHttpReqester(domWin
, url
, sandbox
), "contentStartRequest");
198 sandbox
.GM_addStyle
= tieto(null, function (doc
, cssstr
) {
199 var head
= doc
.getElementsByTagName("head")[0];
201 var style
= doc
.createElement("style");
202 style
.textContent
= cssstr
;
203 style
.type
= "text/css";
204 head
.appendChild(style
);
210 sandbox
.GM_openInTab
= tieto(null, openTab
, domWin
);
212 sandbox
.GM_getResourceText
= tieto(null, function (name
) {
213 if (typeof(name
) === "undefined") throw new Error("GM_getResourceText(): no name given!");
215 let rsrc
= scres
[name
];
216 if (!rsrc
) throw new Error("GM_getResourceText(): no resource found: '"+name
+"'");
217 return fileReadText(rsrc
.file
);
220 sandbox
.GM_getResourceURL
= tieto(null, function (name
) {
221 //logError("GM_getResourceURL(): stub!");
222 //throw new Error("GM_getResourceURL() not implemented");
223 if (typeof(name
) === "undefined") throw new Error("GM_getResourceText(): no name given!");
225 let rsrc
= scres
[name
];
226 if (!rsrc
) throw new Error("GM_getResourceText(): no resource found: '"+name
+"'");
227 let rawdata
= fileReadBinary(rsrc
.file
);
228 return "data:"+rsrc
.contenttype
+";base64,"+encodeURIComponent(btoa(rawdata
));
232 sandbox
.GM_registerMenuCommand
= tieto(null, function () { logError("GM_registerMenuCommand(): stub!"); });
233 sandbox
.GM_setClipboard
= tieto(null, function () { logError("GM_setClipboard(): stub!"); });
236 // provide log functions for both wrapped and unwrapped scripts
237 if (!nfo
.unwrapped
|| nfo
.wantlog
) {
238 sandbox
.conlog
= tieto(null, conlog
);
239 sandbox
.logError
= tieto(null, logError
);
240 if (!nfo
.unwrapped
) sandbox
.GM_log
= tieto(null, conlog
);
243 Object
.defineProperty(sandbox
, "GM_info", {
244 get: tieto(null, function () { logError("GM_info(): stub!"); return {}; }),
251 exports
.runInSandbox = function (sandbox
, nfo
) {
252 // eval the code, with anonymous wrappers when/if appropriate
253 function evalLazyWrap (code
, fileName
) {
255 Cu
.evalInSandbox(code
, sandbox
, "ECMAv5", fileName
, 1);
257 if ("return not in function" == e
.message
) {
258 // we never anon wrap unless forced to by a "return not in a function" error
259 logError("please, do not use `return` in top-level code in "+fileName
+":"+e
.lineNumber
);
260 Cu
.evalInSandbox("(function(){ "+code
+"\n})()", sandbox
, "ECMAv5", fileName
, 1);
268 // eval the code, with a try/catch to report errors cleanly
269 function evalNoThrow (code
, fileName
) {
271 evalLazyWrap(code
, fileName
);
273 logException("UJS", e
);
281 for (let fl
of nfo
.libs
) {
282 if (!fl
.exists() || fl
.isDirectory() || !fl
.isReadable()) return;
283 let text
= fileReadText(fl
);
284 //conlog("*** lib: ", fl.path);
285 if (!evalNoThrow(text
, "libs/"+fl
.name
+".js")) return;
288 for (let fl
of nfo
.incs
) {
289 if (!fl
.exists() || fl
.isDirectory() || !fl
.isReadable()) return;
290 let text
= fileReadText(fl
);
291 //conlog("*** inc: ", fl.path);
292 if (!evalNoThrow(text
, nfo
.name
+"/"+fl
.name
+".js")) return;
296 if (!nfo
.file
.exists() || nfo
.file
.isDirectory() || !nfo
.file
.isReadable()) return;
297 let text
= fileReadText(nfo
.file
);
298 //conlog("*** main: ", nfo.file.path);
299 evalNoThrow(text
, nfo
.name
+".js");
302 logException("XUJS", e
);