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.

342 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/uBlock
  15. */
  16. 'use strict';
  17. /******************************************************************************/
  18. this.EXPORTED_SYMBOLS = ['contentObserver', 'LocationChangeListener'];
  19. const {interfaces: Ci, utils: Cu} = Components;
  20. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  21. const {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  22. const hostName = Services.io.newURI(Components.stack.filename, null, null).host;
  23. // Cu.import('resource://gre/modules/devtools/Console.jsm');
  24. /******************************************************************************/
  25. const getMessageManager = function(win) {
  26. return win
  27. .QueryInterface(Ci.nsIInterfaceRequestor)
  28. .getInterface(Ci.nsIDocShell)
  29. .sameTypeRootTreeItem
  30. .QueryInterface(Ci.nsIDocShell)
  31. .QueryInterface(Ci.nsIInterfaceRequestor)
  32. .getInterface(Ci.nsIContentFrameMessageManager);
  33. };
  34. /******************************************************************************/
  35. const contentObserver = {
  36. classDescription: 'content-policy for ' + hostName,
  37. classID: Components.ID('{7afbd130-cbaf-46c2-b944-f5d24305f484}'),
  38. contractID: '@' + hostName + '/content-policy;1',
  39. ACCEPT: Ci.nsIContentPolicy.ACCEPT,
  40. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  41. contentBaseURI: 'chrome://' + hostName + '/content/js/',
  42. cpMessageName: hostName + ':shouldLoad',
  43. ignoredPopups: new WeakMap(),
  44. uniqueSandboxId: 1,
  45. get componentRegistrar() {
  46. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  47. },
  48. get categoryManager() {
  49. return Components.classes['@mozilla.org/categorymanager;1']
  50. .getService(Ci.nsICategoryManager);
  51. },
  52. QueryInterface: XPCOMUtils.generateQI([
  53. Ci.nsIFactory,
  54. Ci.nsIObserver,
  55. Ci.nsIContentPolicy,
  56. Ci.nsISupportsWeakReference
  57. ]),
  58. createInstance: function(outer, iid) {
  59. if ( outer ) {
  60. throw Components.results.NS_ERROR_NO_AGGREGATION;
  61. }
  62. return this.QueryInterface(iid);
  63. },
  64. register: function() {
  65. Services.obs.addObserver(this, 'document-element-inserted', true);
  66. this.componentRegistrar.registerFactory(
  67. this.classID,
  68. this.classDescription,
  69. this.contractID,
  70. this
  71. );
  72. this.categoryManager.addCategoryEntry(
  73. 'content-policy',
  74. this.contractID,
  75. this.contractID,
  76. false,
  77. true
  78. );
  79. },
  80. unregister: function() {
  81. Services.obs.removeObserver(this, 'document-element-inserted');
  82. this.componentRegistrar.unregisterFactory(this.classID, this);
  83. this.categoryManager.deleteCategoryEntry(
  84. 'content-policy',
  85. this.contractID,
  86. false
  87. );
  88. },
  89. getFrameId: function(win) {
  90. return win
  91. .QueryInterface(Ci.nsIInterfaceRequestor)
  92. .getInterface(Ci.nsIDOMWindowUtils)
  93. .outerWindowID;
  94. },
  95. // https://bugzil.la/612921
  96. shouldLoad: function(type, location, origin, context) {
  97. if ( !context ) {
  98. return this.ACCEPT;
  99. }
  100. if ( !location.schemeIs('http') && !location.schemeIs('https') ) {
  101. return this.ACCEPT;
  102. }
  103. let openerURL = null;
  104. if ( type === this.MAIN_FRAME ) {
  105. context = context.contentWindow || context;
  106. if ( context.opener && context.opener !== context
  107. && this.ignoredPopups.has(context) === false ) {
  108. openerURL = context.opener.location.href;
  109. }
  110. } else if ( type === 7 ) { // SUB_DOCUMENT
  111. context = context.contentWindow;
  112. } else {
  113. context = (context.ownerDocument || context).defaultView;
  114. }
  115. // The context for the toolbar popup is an iframe element here,
  116. // so check context.top instead of context
  117. if ( !context.top || !context.location ) {
  118. return this.ACCEPT;
  119. }
  120. let isTopLevel = context === context.top;
  121. let parentFrameId;
  122. if ( isTopLevel ) {
  123. parentFrameId = -1;
  124. } else if ( context.parent === context.top ) {
  125. parentFrameId = 0;
  126. } else {
  127. parentFrameId = this.getFrameId(context.parent);
  128. }
  129. let messageManager = getMessageManager(context);
  130. let details = {
  131. frameId: isTopLevel ? 0 : this.getFrameId(context),
  132. openerURL: openerURL,
  133. parentFrameId: parentFrameId,
  134. type: type,
  135. url: location.spec
  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. sandbox = Cu.Sandbox([win], {
  155. sandboxName: sandboxId + '[' + sandboxName + ']',
  156. sandboxPrototype: win,
  157. wantComponents: false,
  158. wantXHRConstructor: false
  159. });
  160. sandbox.injectScript = function(script) {
  161. Services.scriptloader.loadSubScript(script, sandbox);
  162. };
  163. }
  164. else {
  165. sandbox = win;
  166. }
  167. sandbox._sandboxId_ = sandboxId;
  168. sandbox.sendAsyncMessage = messager.sendAsyncMessage;
  169. sandbox.addMessageListener = function(callback) {
  170. if ( sandbox._messageListener_ ) {
  171. sandbox.removeMessageListener();
  172. }
  173. sandbox._messageListener_ = function(message) {
  174. callback(message.data);
  175. };
  176. messager.addMessageListener(
  177. sandbox._sandboxId_,
  178. sandbox._messageListener_
  179. );
  180. messager.addMessageListener(
  181. hostName + ':broadcast',
  182. sandbox._messageListener_
  183. );
  184. };
  185. sandbox.removeMessageListener = function() {
  186. try {
  187. messager.removeMessageListener(
  188. sandbox._sandboxId_,
  189. sandbox._messageListener_
  190. );
  191. messager.removeMessageListener(
  192. hostName + ':broadcast',
  193. sandbox._messageListener_
  194. );
  195. } catch (ex) {
  196. // It throws sometimes, mostly when the popup closes
  197. }
  198. sandbox._messageListener_ = null;
  199. };
  200. return sandbox;
  201. },
  202. ignorePopup: function(e) {
  203. if ( e.isTrusted === false ) {
  204. return;
  205. }
  206. let contObs = contentObserver;
  207. contObs.ignoredPopups.set(this, true);
  208. this.removeEventListener('keydown', contObs.ignorePopup, true);
  209. this.removeEventListener('mousedown', contObs.ignorePopup, true);
  210. },
  211. observe: function(doc) {
  212. let win = doc.defaultView;
  213. if ( !win ) {
  214. return;
  215. }
  216. if ( win.opener && this.ignoredPopups.has(win) === false ) {
  217. win.addEventListener('keydown', this.ignorePopup, true);
  218. win.addEventListener('mousedown', this.ignorePopup, true);
  219. }
  220. let loc = win.location;
  221. if ( loc.protocol !== 'http:' && loc.protocol !== 'https:' && loc.protocol !== 'file:' ) {
  222. if ( loc.protocol === 'chrome:' && loc.host === hostName ) {
  223. this.initContentScripts(win);
  224. }
  225. // What about data: and about:blank?
  226. return;
  227. }
  228. let lss = Services.scriptloader.loadSubScript;
  229. let sandbox = this.initContentScripts(win, true);
  230. lss(this.contentBaseURI + 'vapi-client.js', sandbox);
  231. lss(this.contentBaseURI + 'contentscript-start.js', sandbox);
  232. let docReady = (e) => {
  233. let doc = e.target;
  234. doc.removeEventListener(e.type, docReady, true);
  235. lss(this.contentBaseURI + 'contentscript-end.js', sandbox);
  236. if ( doc.querySelector('a[href^="abp:"]') ) {
  237. lss(this.contentBaseURI + 'subscriber.js', sandbox);
  238. }
  239. };
  240. if ( doc.readyState === 'loading') {
  241. doc.addEventListener('DOMContentLoaded', docReady, true);
  242. } else {
  243. docReady({ target: doc, type: 'DOMContentLoaded' });
  244. }
  245. }
  246. };
  247. /******************************************************************************/
  248. const locationChangedMessageName = hostName + ':locationChanged';
  249. const LocationChangeListener = function(docShell) {
  250. if (docShell) {
  251. docShell.QueryInterface(Ci.nsIInterfaceRequestor);
  252. this.docShell = docShell.getInterface(Ci.nsIWebProgress);
  253. this.messageManager = docShell.getInterface(Ci.nsIContentFrameMessageManager);
  254. if (this.messageManager && typeof this.messageManager.sendAsyncMessage === 'function') {
  255. this.docShell.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
  256. }
  257. }
  258. };
  259. LocationChangeListener.prototype.QueryInterface = XPCOMUtils.generateQI(["nsIWebProgressListener", "nsISupportsWeakReference"]);
  260. LocationChangeListener.prototype.onLocationChange = function(webProgress, request, location, flags) {
  261. if ( !webProgress.isTopLevel ) {
  262. return;
  263. }
  264. this.messageManager.sendAsyncMessage(locationChangedMessageName, {
  265. url: location.asciiSpec,
  266. flags: flags,
  267. });
  268. };
  269. /******************************************************************************/
  270. contentObserver.register();
  271. /******************************************************************************/