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.

348 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. modernFirefox: Services.appinfo.ID === '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}' &&
  60. Services.vc.compare(Services.appinfo.platformVersion, '45.0') >= 0,
  61. get componentRegistrar() {
  62. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  63. },
  64. get categoryManager() {
  65. return Components.classes['@mozilla.org/categorymanager;1']
  66. .getService(Ci.nsICategoryManager);
  67. },
  68. QueryInterface: XPCOMUtils.generateQI([
  69. Ci.nsIFactory,
  70. Ci.nsIObserver,
  71. Ci.nsIContentPolicy,
  72. Ci.nsISupportsWeakReference
  73. ]),
  74. createInstance: function(outer, iid) {
  75. if ( outer ) {
  76. throw Components.results.NS_ERROR_NO_AGGREGATION;
  77. }
  78. return this.QueryInterface(iid);
  79. },
  80. register: function() {
  81. Services.obs.addObserver(this, 'document-element-inserted', true);
  82. if ( !this.modernFirefox ) {
  83. this.componentRegistrar.registerFactory(
  84. this.classID,
  85. this.classDescription,
  86. this.contractID,
  87. this
  88. );
  89. this.categoryManager.addCategoryEntry(
  90. 'content-policy',
  91. this.contractID,
  92. this.contractID,
  93. false,
  94. true
  95. );
  96. }
  97. },
  98. unregister: function() {
  99. Services.obs.removeObserver(this, 'document-element-inserted');
  100. if ( !this.modernFirefox ) {
  101. this.componentRegistrar.unregisterFactory(
  102. this.classID,
  103. this
  104. );
  105. this.categoryManager.deleteCategoryEntry(
  106. 'content-policy',
  107. this.contractID,
  108. false
  109. );
  110. }
  111. },
  112. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy
  113. // https://bugzil.la/612921
  114. shouldLoad: function(type, location, origin, context) {
  115. if ( Services === undefined || !context ) {
  116. return this.ACCEPT;
  117. }
  118. if ( !location.schemeIs('http') && !location.schemeIs('https') ) {
  119. return this.ACCEPT;
  120. }
  121. var contextWindow;
  122. if ( type === this.MAIN_FRAME ) {
  123. contextWindow = context.contentWindow || context;
  124. } else if ( type === this.SUB_FRAME ) {
  125. contextWindow = context.contentWindow;
  126. } else {
  127. contextWindow = (context.ownerDocument || context).defaultView;
  128. }
  129. // The context for the toolbar popup is an iframe element here,
  130. // so check context.top instead of context
  131. if ( !contextWindow.top || !contextWindow.location ) {
  132. return this.ACCEPT;
  133. }
  134. let messageManager = getMessageManager(contextWindow);
  135. if ( messageManager === null ) {
  136. return this.ACCEPT;
  137. }
  138. let details = {
  139. rawType: type,
  140. url: location.asciiSpec
  141. };
  142. if ( typeof messageManager.sendRpcMessage === 'function' ) {
  143. // https://bugzil.la/1092216
  144. messageManager.sendRpcMessage(this.cpMessageName, details);
  145. } else {
  146. // Compatibility for older versions
  147. messageManager.sendSyncMessage(this.cpMessageName, details);
  148. }
  149. return this.ACCEPT;
  150. },
  151. initContentScripts: function(win, sandbox) {
  152. let messager = getMessageManager(win);
  153. let sandboxId = hostName + ':sb:' + this.uniqueSandboxId++;
  154. if ( sandbox ) {
  155. let sandboxName = [
  156. win.location.href.slice(0, 100),
  157. win.document.title.slice(0, 100)
  158. ].join(' | ');
  159. // https://github.com/gorhill/uMatrix/issues/325
  160. // "Pass sameZoneAs to sandbox constructor to make GCs cheaper"
  161. sandbox = Cu.Sandbox([win], {
  162. sameZoneAs: win.top,
  163. sandboxName: sandboxId + '[' + sandboxName + ']',
  164. sandboxPrototype: win,
  165. wantComponents: false,
  166. wantXHRConstructor: false
  167. });
  168. sandbox.injectScript = function(script) {
  169. Services.scriptloader.loadSubScript(script, sandbox);
  170. };
  171. }
  172. else {
  173. sandbox = win;
  174. }
  175. sandbox._sandboxId_ = sandboxId;
  176. sandbox.sendAsyncMessage = messager.sendAsyncMessage;
  177. sandbox.addMessageListener = function(callback) {
  178. if ( sandbox._messageListener_ ) {
  179. sandbox.removeMessageListener();
  180. }
  181. sandbox._messageListener_ = function(message) {
  182. callback(message.data);
  183. };
  184. messager.addMessageListener(
  185. sandbox._sandboxId_,
  186. sandbox._messageListener_
  187. );
  188. messager.addMessageListener(
  189. hostName + ':broadcast',
  190. sandbox._messageListener_
  191. );
  192. };
  193. sandbox.removeMessageListener = function() {
  194. try {
  195. messager.removeMessageListener(
  196. sandbox._sandboxId_,
  197. sandbox._messageListener_
  198. );
  199. messager.removeMessageListener(
  200. hostName + ':broadcast',
  201. sandbox._messageListener_
  202. );
  203. } catch (ex) {
  204. // It throws sometimes, mostly when the popup closes
  205. }
  206. sandbox._messageListener_ = null;
  207. };
  208. return sandbox;
  209. },
  210. observe: function(doc) {
  211. let win = doc.defaultView;
  212. if ( !win ) {
  213. return;
  214. }
  215. let loc = win.location;
  216. if ( !loc ) {
  217. return;
  218. }
  219. // https://github.com/gorhill/uBlock/issues/260
  220. // TODO: We may have to skip more types, for now let's be
  221. // conservative, i.e. let's not test against `text/html`.
  222. if ( doc.contentType.lastIndexOf('image/', 0) === 0 ) {
  223. return;
  224. }
  225. if ( loc.protocol !== 'http:' && loc.protocol !== 'https:' && loc.protocol !== 'file:' ) {
  226. if ( loc.protocol === 'chrome:' && loc.host === hostName ) {
  227. this.initContentScripts(win);
  228. }
  229. // What about data: and about:blank?
  230. return;
  231. }
  232. let lss = Services.scriptloader.loadSubScript;
  233. let sandbox = this.initContentScripts(win, true);
  234. // Can throw with attempts at injecting into non-HTML document.
  235. // Example: https://a.pomf.se/avonjf.webm
  236. try {
  237. lss(this.contentBaseURI + 'vapi-client.js', sandbox);
  238. lss(this.contentBaseURI + 'contentscript-start.js', sandbox);
  239. } catch (ex) {
  240. return; // don't further try to inject anything
  241. }
  242. let docReady = (e) => {
  243. let doc = e.target;
  244. doc.removeEventListener(e.type, docReady, true);
  245. lss(this.contentBaseURI + 'contentscript-end.js', sandbox);
  246. };
  247. if ( doc.readyState === 'loading') {
  248. doc.addEventListener('DOMContentLoaded', docReady, true);
  249. } else {
  250. docReady({ target: doc, type: 'DOMContentLoaded' });
  251. }
  252. }
  253. };
  254. /******************************************************************************/
  255. const locationChangedMessageName = hostName + ':locationChanged';
  256. var LocationChangeListener = function(docShell) {
  257. if ( !docShell ) {
  258. return;
  259. }
  260. var requestor = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
  261. var ds = requestor.getInterface(Ci.nsIWebProgress);
  262. var mm = requestor.getInterface(Ci.nsIContentFrameMessageManager);
  263. if ( ds && mm && typeof mm.sendAsyncMessage === 'function' ) {
  264. this.docShell = ds;
  265. this.messageManager = mm;
  266. ds.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
  267. }
  268. };
  269. LocationChangeListener.prototype.QueryInterface = XPCOMUtils.generateQI([
  270. 'nsIWebProgressListener',
  271. 'nsISupportsWeakReference'
  272. ]);
  273. LocationChangeListener.prototype.onLocationChange = function(webProgress, request, location, flags) {
  274. if ( !webProgress.isTopLevel ) {
  275. return;
  276. }
  277. this.messageManager.sendAsyncMessage(locationChangedMessageName, {
  278. url: location.asciiSpec,
  279. flags: flags,
  280. });
  281. };
  282. /******************************************************************************/
  283. contentObserver.register();
  284. /******************************************************************************/