You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

343 lines
11 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. µBlock - a browser extension to block requests.
  3. Copyright (C) 2014 The µBlock authors
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see {http://www.gnu.org/licenses/}.
  14. Home: https://github.com/gorhill/uMatrix
  15. */
  16. /* global Components */
  17. 'use strict';
  18. /******************************************************************************/
  19. // https://github.com/gorhill/uBlock/issues/800#issuecomment-146580443
  20. this.EXPORTED_SYMBOLS = ['contentObserver', 'LocationChangeListener'];
  21. const {interfaces: Ci, utils: Cu} = Components;
  22. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  23. const {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  24. const hostName = Services.io.newURI(Components.stack.filename, null, null).host;
  25. // Cu.import('resource://gre/modules/devtools/Console.jsm');
  26. /******************************************************************************/
  27. const getMessageManager = function(win) {
  28. let iface = win
  29. .QueryInterface(Ci.nsIInterfaceRequestor)
  30. .getInterface(Ci.nsIDocShell)
  31. .sameTypeRootTreeItem
  32. .QueryInterface(Ci.nsIDocShell)
  33. .QueryInterface(Ci.nsIInterfaceRequestor);
  34. try {
  35. return iface.getInterface(Ci.nsIContentFrameMessageManager);
  36. } catch (ex) {
  37. // This can throw. It appears `shouldLoad` can be called *after* a
  38. // tab has been closed. For example, a case where this happens all
  39. // the time (FF38):
  40. // - Open twitter.com (assuming you have an account and are logged in)
  41. // - Close twitter.com
  42. // There will be an exception raised when `shouldLoad` is called
  43. // to process a XMLHttpRequest with URL `https://twitter.com/i/jot`
  44. // fired from `https://twitter.com/`, *after* the tab is closed.
  45. // In such case, `win` is `about:blank`.
  46. }
  47. return null;
  48. };
  49. /******************************************************************************/
  50. var contentObserver = {
  51. classDescription: 'content-policy for ' + hostName,
  52. classID: Components.ID('{c84283d4-9975-41b7-b1a4-f106af56b51d}'),
  53. contractID: '@' + hostName + '/content-policy;1',
  54. ACCEPT: Ci.nsIContentPolicy.ACCEPT,
  55. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  56. contentBaseURI: 'chrome://' + hostName + '/content/js/',
  57. cpMessageName: hostName + ':shouldLoad',
  58. uniqueSandboxId: 1,
  59. firefoxPre35: Services.vc.compare(Services.appinfo.platformVersion, '35.0') < 0,
  60. get componentRegistrar() {
  61. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  62. },
  63. get categoryManager() {
  64. return Components.classes['@mozilla.org/categorymanager;1']
  65. .getService(Ci.nsICategoryManager);
  66. },
  67. QueryInterface: XPCOMUtils.generateQI([
  68. Ci.nsIFactory,
  69. Ci.nsIObserver,
  70. Ci.nsIContentPolicy,
  71. Ci.nsISupportsWeakReference
  72. ]),
  73. createInstance: function(outer, iid) {
  74. if ( outer ) {
  75. throw Components.results.NS_ERROR_NO_AGGREGATION;
  76. }
  77. return this.QueryInterface(iid);
  78. },
  79. register: function() {
  80. Services.obs.addObserver(this, 'document-element-inserted', true);
  81. this.componentRegistrar.registerFactory(
  82. this.classID,
  83. this.classDescription,
  84. this.contractID,
  85. this
  86. );
  87. this.categoryManager.addCategoryEntry(
  88. 'content-policy',
  89. this.contractID,
  90. this.contractID,
  91. false,
  92. true
  93. );
  94. },
  95. unregister: function() {
  96. Services.obs.removeObserver(this, 'document-element-inserted');
  97. this.componentRegistrar.unregisterFactory(
  98. this.classID,
  99. this
  100. );
  101. this.categoryManager.deleteCategoryEntry(
  102. 'content-policy',
  103. this.contractID,
  104. false
  105. );
  106. },
  107. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy
  108. // https://bugzil.la/612921
  109. shouldLoad: function(type, location, origin, context) {
  110. if ( Services === undefined || !context ) {
  111. return this.ACCEPT;
  112. }
  113. if ( !location.schemeIs('http') && !location.schemeIs('https') ) {
  114. return this.ACCEPT;
  115. }
  116. var contextWindow;
  117. if ( type === this.MAIN_FRAME ) {
  118. contextWindow = context.contentWindow || context;
  119. } else if ( type === this.SUB_FRAME ) {
  120. contextWindow = context.contentWindow;
  121. } else {
  122. contextWindow = (context.ownerDocument || context).defaultView;
  123. }
  124. // The context for the toolbar popup is an iframe element here,
  125. // so check context.top instead of context
  126. if ( !contextWindow.top || !contextWindow.location ) {
  127. return this.ACCEPT;
  128. }
  129. let messageManager = getMessageManager(contextWindow);
  130. if ( messageManager === null ) {
  131. return this.ACCEPT;
  132. }
  133. let details = {
  134. rawType: type,
  135. url: location.asciiSpec
  136. };
  137. if ( typeof messageManager.sendRpcMessage === 'function' ) {
  138. // https://bugzil.la/1092216
  139. messageManager.sendRpcMessage(this.cpMessageName, details);
  140. } else {
  141. // Compatibility for older versions
  142. messageManager.sendSyncMessage(this.cpMessageName, details);
  143. }
  144. return this.ACCEPT;
  145. },
  146. initContentScripts: function(win, sandbox) {
  147. let messager = getMessageManager(win);
  148. let sandboxId = hostName + ':sb:' + this.uniqueSandboxId++;
  149. if ( sandbox ) {
  150. let sandboxName = [
  151. win.location.href.slice(0, 100),
  152. win.document.title.slice(0, 100)
  153. ].join(' | ');
  154. // https://github.com/gorhill/uMatrix/issues/325
  155. // "Pass sameZoneAs to sandbox constructor to make GCs cheaper"
  156. sandbox = Cu.Sandbox([win], {
  157. sameZoneAs: win.top,
  158. sandboxName: sandboxId + '[' + sandboxName + ']',
  159. sandboxPrototype: win,
  160. wantComponents: false,
  161. wantXHRConstructor: false
  162. });
  163. sandbox.injectScript = function(script) {
  164. Services.scriptloader.loadSubScript(script, sandbox);
  165. };
  166. }
  167. else {
  168. sandbox = win;
  169. }
  170. sandbox._sandboxId_ = sandboxId;
  171. sandbox.sendAsyncMessage = messager.sendAsyncMessage;
  172. sandbox.addMessageListener = function(callback) {
  173. if ( sandbox._messageListener_ ) {
  174. sandbox.removeMessageListener();
  175. }
  176. sandbox._messageListener_ = function(message) {
  177. callback(message.data);
  178. };
  179. messager.addMessageListener(
  180. sandbox._sandboxId_,
  181. sandbox._messageListener_
  182. );
  183. messager.addMessageListener(
  184. hostName + ':broadcast',
  185. sandbox._messageListener_
  186. );
  187. };
  188. sandbox.removeMessageListener = function() {
  189. try {
  190. messager.removeMessageListener(
  191. sandbox._sandboxId_,
  192. sandbox._messageListener_
  193. );
  194. messager.removeMessageListener(
  195. hostName + ':broadcast',
  196. sandbox._messageListener_
  197. );
  198. } catch (ex) {
  199. // It throws sometimes, mostly when the popup closes
  200. }
  201. sandbox._messageListener_ = null;
  202. };
  203. return sandbox;
  204. },
  205. observe: function(doc) {
  206. let win = doc.defaultView;
  207. if ( !win ) {
  208. return;
  209. }
  210. let loc = win.location;
  211. if ( !loc ) {
  212. return;
  213. }
  214. // https://github.com/gorhill/uBlock/issues/260
  215. // TODO: We may have to skip more types, for now let's be
  216. // conservative, i.e. let's not test against `text/html`.
  217. if ( doc.contentType.lastIndexOf('image/', 0) === 0 ) {
  218. return;
  219. }
  220. if ( loc.protocol !== 'http:' && loc.protocol !== 'https:' && loc.protocol !== 'file:' ) {
  221. if ( loc.protocol === 'chrome:' && loc.host === hostName ) {
  222. this.initContentScripts(win);
  223. }
  224. // What about data: and about:blank?
  225. return;
  226. }
  227. let lss = Services.scriptloader.loadSubScript;
  228. let sandbox = this.initContentScripts(win, true);
  229. // Can throw with attempts at injecting into non-HTML document.
  230. // Example: https://a.pomf.se/avonjf.webm
  231. try {
  232. lss(this.contentBaseURI + 'vapi-client.js', sandbox);
  233. lss(this.contentBaseURI + 'contentscript-start.js', sandbox);
  234. } catch (ex) {
  235. return; // don't further try to inject anything
  236. }
  237. let docReady = (e) => {
  238. let doc = e.target;
  239. doc.removeEventListener(e.type, docReady, true);
  240. lss(this.contentBaseURI + 'contentscript-end.js', sandbox);
  241. };
  242. if ( doc.readyState === 'loading') {
  243. doc.addEventListener('DOMContentLoaded', docReady, true);
  244. } else {
  245. docReady({ target: doc, type: 'DOMContentLoaded' });
  246. }
  247. }
  248. };
  249. /******************************************************************************/
  250. const locationChangedMessageName = hostName + ':locationChanged';
  251. var LocationChangeListener = function(docShell) {
  252. if ( !docShell ) {
  253. return;
  254. }
  255. var requestor = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
  256. var ds = requestor.getInterface(Ci.nsIWebProgress);
  257. var mm = requestor.getInterface(Ci.nsIContentFrameMessageManager);
  258. if ( ds && mm && typeof mm.sendAsyncMessage === 'function' ) {
  259. this.docShell = ds;
  260. this.messageManager = mm;
  261. ds.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
  262. }
  263. };
  264. LocationChangeListener.prototype.QueryInterface = XPCOMUtils.generateQI([
  265. 'nsIWebProgressListener',
  266. 'nsISupportsWeakReference'
  267. ]);
  268. LocationChangeListener.prototype.onLocationChange = function(webProgress, request, location, flags) {
  269. if ( !webProgress.isTopLevel ) {
  270. return;
  271. }
  272. this.messageManager.sendAsyncMessage(locationChangedMessageName, {
  273. url: location.asciiSpec,
  274. flags: flags,
  275. });
  276. };
  277. /******************************************************************************/
  278. contentObserver.register();
  279. /******************************************************************************/