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.

278 lines
8.7 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
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. this.EXPORTED_SYMBOLS = ['contentObserver', 'LocationChangeListener'];
  20. const {interfaces: Ci, utils: Cu} = Components;
  21. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  22. const {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  23. const hostName = Services.io.newURI(Components.stack.filename, null, null).host;
  24. // Cu.import('resource://gre/modules/devtools/Console.jsm');
  25. /******************************************************************************/
  26. const getMessageManager = function(win) {
  27. return win
  28. .QueryInterface(Ci.nsIInterfaceRequestor)
  29. .getInterface(Ci.nsIDocShell)
  30. .sameTypeRootTreeItem
  31. .QueryInterface(Ci.nsIDocShell)
  32. .QueryInterface(Ci.nsIInterfaceRequestor)
  33. .getInterface(Ci.nsIContentFrameMessageManager);
  34. };
  35. /******************************************************************************/
  36. const contentObserver = {
  37. classDescription: 'content-policy for ' + hostName,
  38. classID: Components.ID('{c84283d4-9975-41b7-b1a4-f106af56b51d}'),
  39. contractID: '@' + hostName + '/content-policy;1',
  40. ACCEPT: Ci.nsIContentPolicy.ACCEPT,
  41. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  42. contentBaseURI: 'chrome://' + hostName + '/content/js/',
  43. uniqueSandboxId: 1,
  44. get componentRegistrar() {
  45. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  46. },
  47. get categoryManager() {
  48. return Components.classes['@mozilla.org/categorymanager;1']
  49. .getService(Ci.nsICategoryManager);
  50. },
  51. QueryInterface: XPCOMUtils.generateQI([
  52. Ci.nsIFactory,
  53. Ci.nsIObserver,
  54. Ci.nsIContentPolicy,
  55. Ci.nsISupportsWeakReference
  56. ]),
  57. createInstance: function(outer, iid) {
  58. if ( outer ) {
  59. throw Components.results.NS_ERROR_NO_AGGREGATION;
  60. }
  61. return this.QueryInterface(iid);
  62. },
  63. register: function() {
  64. Services.obs.addObserver(this, 'document-element-inserted', true);
  65. this.componentRegistrar.registerFactory(
  66. this.classID,
  67. this.classDescription,
  68. this.contractID,
  69. this
  70. );
  71. this.categoryManager.addCategoryEntry(
  72. 'content-policy',
  73. this.contractID,
  74. this.contractID,
  75. false,
  76. true
  77. );
  78. },
  79. unregister: function() {
  80. Services.obs.removeObserver(this, 'document-element-inserted');
  81. this.componentRegistrar.unregisterFactory(this.classID, this);
  82. this.categoryManager.deleteCategoryEntry(
  83. 'content-policy',
  84. this.contractID,
  85. false
  86. );
  87. },
  88. // https://bugzil.la/612921
  89. shouldLoad: function(type, location, origin, context) {
  90. return this.ACCEPT;
  91. },
  92. initContentScripts: function(win, sandbox) {
  93. let messager = getMessageManager(win);
  94. let sandboxId = hostName + ':sb:' + this.uniqueSandboxId++;
  95. if ( sandbox ) {
  96. let sandboxName = [
  97. win.location.href.slice(0, 100),
  98. win.document.title.slice(0, 100)
  99. ].join(' | ');
  100. sandbox = Cu.Sandbox([win], {
  101. sandboxName: sandboxId + '[' + sandboxName + ']',
  102. sandboxPrototype: win,
  103. wantComponents: false,
  104. wantXHRConstructor: false
  105. });
  106. sandbox.injectScript = function(script) {
  107. Services.scriptloader.loadSubScript(script, sandbox);
  108. };
  109. }
  110. else {
  111. sandbox = win;
  112. }
  113. sandbox._sandboxId_ = sandboxId;
  114. sandbox.sendAsyncMessage = messager.sendAsyncMessage;
  115. sandbox.addMessageListener = function(callback) {
  116. if ( sandbox._messageListener_ ) {
  117. sandbox.removeMessageListener();
  118. }
  119. sandbox._messageListener_ = function(message) {
  120. callback(message.data);
  121. };
  122. messager.addMessageListener(
  123. sandbox._sandboxId_,
  124. sandbox._messageListener_
  125. );
  126. messager.addMessageListener(
  127. hostName + ':broadcast',
  128. sandbox._messageListener_
  129. );
  130. };
  131. sandbox.removeMessageListener = function() {
  132. try {
  133. messager.removeMessageListener(
  134. sandbox._sandboxId_,
  135. sandbox._messageListener_
  136. );
  137. messager.removeMessageListener(
  138. hostName + ':broadcast',
  139. sandbox._messageListener_
  140. );
  141. } catch (ex) {
  142. // It throws sometimes, mostly when the popup closes
  143. }
  144. sandbox._messageListener_ = null;
  145. };
  146. return sandbox;
  147. },
  148. observe: function(doc) {
  149. let win = doc.defaultView;
  150. if ( !win ) {
  151. return;
  152. }
  153. let loc = win.location;
  154. if ( !loc ) {
  155. return;
  156. }
  157. // https://github.com/gorhill/uBlock/issues/260
  158. // TODO: We may have to skip more types, for now let's be
  159. // conservative, i.e. let's not test against `text/html`.
  160. if ( doc.contentType.lastIndexOf('image/', 0) === 0 ) {
  161. return;
  162. }
  163. if ( loc.protocol !== 'http:' && loc.protocol !== 'https:' && loc.protocol !== 'file:' ) {
  164. if ( loc.protocol === 'chrome:' && loc.host === hostName ) {
  165. this.initContentScripts(win);
  166. }
  167. // What about data: and about:blank?
  168. return;
  169. }
  170. let lss = Services.scriptloader.loadSubScript;
  171. let sandbox = this.initContentScripts(win, true);
  172. // Can throw with attempts at injecting into non-HTML document.
  173. // Example: https://a.pomf.se/avonjf.webm
  174. try {
  175. lss(this.contentBaseURI + 'vapi-client.js', sandbox);
  176. lss(this.contentBaseURI + 'contentscript-start.js', sandbox);
  177. } catch (ex) {
  178. return; // don't further try to inject anything
  179. }
  180. let docReady = (e) => {
  181. let doc = e.target;
  182. doc.removeEventListener(e.type, docReady, true);
  183. lss(this.contentBaseURI + 'contentscript-end.js', sandbox);
  184. };
  185. if ( doc.readyState === 'loading') {
  186. doc.addEventListener('DOMContentLoaded', docReady, true);
  187. } else {
  188. docReady({ target: doc, type: 'DOMContentLoaded' });
  189. }
  190. }
  191. };
  192. /******************************************************************************/
  193. const locationChangedMessageName = hostName + ':locationChanged';
  194. const LocationChangeListener = function(docShell) {
  195. if ( !docShell ) {
  196. return;
  197. }
  198. var requestor = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
  199. var ds = requestor.getInterface(Ci.nsIWebProgress);
  200. var mm = requestor.getInterface(Ci.nsIContentFrameMessageManager);
  201. if ( ds && mm && typeof mm.sendAsyncMessage === 'function' ) {
  202. this.docShell = ds;
  203. this.messageManager = mm;
  204. ds.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
  205. }
  206. };
  207. LocationChangeListener.prototype.QueryInterface = XPCOMUtils.generateQI([
  208. 'nsIWebProgressListener',
  209. 'nsISupportsWeakReference'
  210. ]);
  211. LocationChangeListener.prototype.onLocationChange = function(webProgress, request, location, flags) {
  212. if ( !webProgress.isTopLevel ) {
  213. return;
  214. }
  215. this.messageManager.sendAsyncMessage(locationChangedMessageName, {
  216. url: location.asciiSpec,
  217. flags: flags,
  218. });
  219. };
  220. /******************************************************************************/
  221. contentObserver.register();
  222. /******************************************************************************/