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.

338 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
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. let iface = win
  28. .QueryInterface(Ci.nsIInterfaceRequestor)
  29. .getInterface(Ci.nsIDocShell)
  30. .sameTypeRootTreeItem
  31. .QueryInterface(Ci.nsIDocShell)
  32. .QueryInterface(Ci.nsIInterfaceRequestor);
  33. try {
  34. return iface.getInterface(Ci.nsIContentFrameMessageManager);
  35. } catch (ex) {
  36. // This can throw. It appears `shouldLoad` can be called *after* a
  37. // tab has been closed. For example, a case where this happens all
  38. // the time (FF38):
  39. // - Open twitter.com (assuming you have an account and are logged in)
  40. // - Close twitter.com
  41. // There will be an exception raised when `shouldLoad` is called
  42. // to process a XMLHttpRequest with URL `https://twitter.com/i/jot`
  43. // fired from `https://twitter.com/`, *after* the tab is closed.
  44. // In such case, `win` is `about:blank`.
  45. }
  46. return null;
  47. };
  48. /******************************************************************************/
  49. const contentObserver = {
  50. classDescription: 'content-policy for ' + hostName,
  51. classID: Components.ID('{c84283d4-9975-41b7-b1a4-f106af56b51d}'),
  52. contractID: '@' + hostName + '/content-policy;1',
  53. ACCEPT: Ci.nsIContentPolicy.ACCEPT,
  54. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  55. contentBaseURI: 'chrome://' + hostName + '/content/js/',
  56. cpMessageName: hostName + ':shouldLoad',
  57. uniqueSandboxId: 1,
  58. get componentRegistrar() {
  59. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  60. },
  61. get categoryManager() {
  62. return Components.classes['@mozilla.org/categorymanager;1']
  63. .getService(Ci.nsICategoryManager);
  64. },
  65. QueryInterface: XPCOMUtils.generateQI([
  66. Ci.nsIFactory,
  67. Ci.nsIObserver,
  68. Ci.nsIContentPolicy,
  69. Ci.nsISupportsWeakReference
  70. ]),
  71. createInstance: function(outer, iid) {
  72. if ( outer ) {
  73. throw Components.results.NS_ERROR_NO_AGGREGATION;
  74. }
  75. return this.QueryInterface(iid);
  76. },
  77. register: function() {
  78. Services.obs.addObserver(this, 'document-element-inserted', true);
  79. this.componentRegistrar.registerFactory(
  80. this.classID,
  81. this.classDescription,
  82. this.contractID,
  83. this
  84. );
  85. this.categoryManager.addCategoryEntry(
  86. 'content-policy',
  87. this.contractID,
  88. this.contractID,
  89. false,
  90. true
  91. );
  92. },
  93. unregister: function() {
  94. Services.obs.removeObserver(this, 'document-element-inserted');
  95. this.componentRegistrar.unregisterFactory(this.classID, this);
  96. this.categoryManager.deleteCategoryEntry(
  97. 'content-policy',
  98. this.contractID,
  99. false
  100. );
  101. },
  102. // https://bugzil.la/612921
  103. shouldLoad: function(type, location, origin, context) {
  104. if ( Services === undefined ) {
  105. return this.ACCEPT;
  106. }
  107. if ( !context ) {
  108. return this.ACCEPT;
  109. }
  110. if ( !location.schemeIs('http') && !location.schemeIs('https') ) {
  111. return this.ACCEPT;
  112. }
  113. var contextWindow;
  114. if ( type === this.MAIN_FRAME ) {
  115. contextWindow = context.contentWindow || context;
  116. } else if ( type === this.SUB_FRAME ) {
  117. contextWindow = context.contentWindow;
  118. } else {
  119. contextWindow = (context.ownerDocument || context).defaultView;
  120. }
  121. // The context for the toolbar popup is an iframe element here,
  122. // so check context.top instead of context
  123. if ( !contextWindow.top || !contextWindow.location ) {
  124. return this.ACCEPT;
  125. }
  126. let messageManager = getMessageManager(contextWindow);
  127. if ( messageManager === null ) {
  128. return this.ACCEPT;
  129. }
  130. let details = {
  131. rawType: type,
  132. url: location.asciiSpec
  133. };
  134. if ( typeof messageManager.sendRpcMessage === 'function' ) {
  135. // https://bugzil.la/1092216
  136. messageManager.sendRpcMessage(this.cpMessageName, details);
  137. } else {
  138. // Compatibility for older versions
  139. messageManager.sendSyncMessage(this.cpMessageName, details);
  140. }
  141. return this.ACCEPT;
  142. },
  143. initContentScripts: function(win, sandbox) {
  144. let messager = getMessageManager(win);
  145. let sandboxId = hostName + ':sb:' + this.uniqueSandboxId++;
  146. if ( sandbox ) {
  147. let sandboxName = [
  148. win.location.href.slice(0, 100),
  149. win.document.title.slice(0, 100)
  150. ].join(' | ');
  151. sandbox = Cu.Sandbox([win], {
  152. sandboxName: sandboxId + '[' + sandboxName + ']',
  153. sandboxPrototype: win,
  154. wantComponents: false,
  155. wantXHRConstructor: false
  156. });
  157. sandbox.injectScript = function(script) {
  158. Services.scriptloader.loadSubScript(script, sandbox);
  159. };
  160. }
  161. else {
  162. sandbox = win;
  163. }
  164. sandbox._sandboxId_ = sandboxId;
  165. sandbox.sendAsyncMessage = messager.sendAsyncMessage;
  166. sandbox.addMessageListener = function(callback) {
  167. if ( sandbox._messageListener_ ) {
  168. sandbox.removeMessageListener();
  169. }
  170. sandbox._messageListener_ = function(message) {
  171. callback(message.data);
  172. };
  173. messager.addMessageListener(
  174. sandbox._sandboxId_,
  175. sandbox._messageListener_
  176. );
  177. messager.addMessageListener(
  178. hostName + ':broadcast',
  179. sandbox._messageListener_
  180. );
  181. };
  182. sandbox.removeMessageListener = function() {
  183. try {
  184. messager.removeMessageListener(
  185. sandbox._sandboxId_,
  186. sandbox._messageListener_
  187. );
  188. messager.removeMessageListener(
  189. hostName + ':broadcast',
  190. sandbox._messageListener_
  191. );
  192. } catch (ex) {
  193. // It throws sometimes, mostly when the popup closes
  194. }
  195. sandbox._messageListener_ = null;
  196. };
  197. return sandbox;
  198. },
  199. observe: function(doc) {
  200. let win = doc.defaultView;
  201. if ( !win ) {
  202. return;
  203. }
  204. let loc = win.location;
  205. if ( !loc ) {
  206. return;
  207. }
  208. // https://github.com/gorhill/uBlock/issues/260
  209. // TODO: We may have to skip more types, for now let's be
  210. // conservative, i.e. let's not test against `text/html`.
  211. if ( doc.contentType.lastIndexOf('image/', 0) === 0 ) {
  212. return;
  213. }
  214. if ( loc.protocol !== 'http:' && loc.protocol !== 'https:' && loc.protocol !== 'file:' ) {
  215. if ( loc.protocol === 'chrome:' && loc.host === hostName ) {
  216. this.initContentScripts(win);
  217. }
  218. // What about data: and about:blank?
  219. return;
  220. }
  221. let lss = Services.scriptloader.loadSubScript;
  222. let sandbox = this.initContentScripts(win, true);
  223. // Can throw with attempts at injecting into non-HTML document.
  224. // Example: https://a.pomf.se/avonjf.webm
  225. try {
  226. lss(this.contentBaseURI + 'vapi-client.js', sandbox);
  227. lss(this.contentBaseURI + 'contentscript-start.js', sandbox);
  228. } catch (ex) {
  229. return; // don't further try to inject anything
  230. }
  231. let docReady = (e) => {
  232. let doc = e.target;
  233. doc.removeEventListener(e.type, docReady, true);
  234. lss(this.contentBaseURI + 'contentscript-end.js', sandbox);
  235. };
  236. if ( doc.readyState === 'loading') {
  237. doc.addEventListener('DOMContentLoaded', docReady, true);
  238. } else {
  239. docReady({ target: doc, type: 'DOMContentLoaded' });
  240. }
  241. }
  242. };
  243. /******************************************************************************/
  244. const locationChangedMessageName = hostName + ':locationChanged';
  245. const LocationChangeListener = function(docShell) {
  246. if ( !docShell ) {
  247. return;
  248. }
  249. var requestor = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
  250. var ds = requestor.getInterface(Ci.nsIWebProgress);
  251. var mm = requestor.getInterface(Ci.nsIContentFrameMessageManager);
  252. if ( ds && mm && typeof mm.sendAsyncMessage === 'function' ) {
  253. this.docShell = ds;
  254. this.messageManager = mm;
  255. ds.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
  256. }
  257. };
  258. LocationChangeListener.prototype.QueryInterface = XPCOMUtils.generateQI([
  259. 'nsIWebProgressListener',
  260. 'nsISupportsWeakReference'
  261. ]);
  262. LocationChangeListener.prototype.onLocationChange = function(webProgress, request, location, flags) {
  263. if ( !webProgress.isTopLevel ) {
  264. return;
  265. }
  266. this.messageManager.sendAsyncMessage(locationChangedMessageName, {
  267. url: location.asciiSpec,
  268. flags: flags,
  269. });
  270. };
  271. /******************************************************************************/
  272. contentObserver.register();
  273. /******************************************************************************/