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.

3105 lines
96 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 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
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
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 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
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
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
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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 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
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
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. /* jshint bitwise: false, esnext: true */
  17. /* global self, Components, punycode, µBlock */
  18. // For background page
  19. /******************************************************************************/
  20. (function() {
  21. 'use strict';
  22. /******************************************************************************/
  23. // Useful links
  24. //
  25. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface
  26. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm
  27. /******************************************************************************/
  28. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  29. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  30. /******************************************************************************/
  31. var vAPI = self.vAPI = self.vAPI || {};
  32. vAPI.firefox = true;
  33. vAPI.modernFirefox = Services.appinfo.ID === '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}' &&
  34. Services.vc.compare(Services.appinfo.platformVersion, '45.0') >= 0;
  35. /******************************************************************************/
  36. vAPI.app = {
  37. name: 'uMatrix',
  38. version: location.hash.slice(1)
  39. };
  40. /******************************************************************************/
  41. vAPI.app.start = function() {
  42. };
  43. /******************************************************************************/
  44. vAPI.app.stop = function() {
  45. };
  46. /******************************************************************************/
  47. vAPI.app.restart = function() {
  48. // Listening in bootstrap.js
  49. Cc['@mozilla.org/childprocessmessagemanager;1']
  50. .getService(Ci.nsIMessageSender)
  51. .sendAsyncMessage(location.host + '-restart');
  52. };
  53. /******************************************************************************/
  54. // https://stackoverflow.com/questions/6715571/how-to-get-result-of-console-trace-as-string-in-javascript-with-chrome-or-fire/28118170#28118170
  55. /*
  56. function logStackTrace(msg) {
  57. var stack;
  58. try {
  59. throw new Error('');
  60. }
  61. catch (error) {
  62. stack = error.stack || '';
  63. }
  64. stack = stack.split('\n').map(function(line) { return line.trim(); });
  65. stack.shift();
  66. if ( msg ) {
  67. stack.unshift(msg);
  68. }
  69. console.log(stack.join('\n'));
  70. }
  71. */
  72. /******************************************************************************/
  73. // List of things that needs to be destroyed when disabling the extension
  74. // Only functions should be added to it
  75. var cleanupTasks = [];
  76. // This must be updated manually, every time a new task is added/removed
  77. // Fixed by github.com/AlexVallat:
  78. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  79. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  80. var expectedNumberOfCleanups = 7;
  81. window.addEventListener('unload', function() {
  82. if ( typeof vAPI.app.onShutdown === 'function' ) {
  83. vAPI.app.onShutdown();
  84. }
  85. for ( var cleanup of cleanupTasks ) {
  86. cleanup();
  87. }
  88. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  89. console.error(
  90. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  91. cleanupTasks.length,
  92. expectedNumberOfCleanups
  93. );
  94. }
  95. // frameModule needs to be cleared too
  96. var frameModule = {};
  97. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  98. frameModule.contentObserver.unregister();
  99. Cu.unload(vAPI.getURL('frameModule.js'));
  100. });
  101. /******************************************************************************/
  102. // For now, only booleans.
  103. vAPI.browserSettings = {
  104. originalValues: {},
  105. rememberOriginalValue: function(branch, setting) {
  106. var key = branch + '.' + setting;
  107. if ( this.originalValues.hasOwnProperty(key) ) {
  108. return;
  109. }
  110. var hasUserValue = false;
  111. try {
  112. hasUserValue = Services.prefs.getBranch(branch + '.').prefHasUserValue(setting);
  113. } catch (ex) {
  114. }
  115. this.originalValues[key] = hasUserValue ? this.getBool(branch, setting) : undefined;
  116. },
  117. clear: function(branch, setting) {
  118. var key = branch + '.' + setting;
  119. // Value was not overriden -- nothing to restore
  120. if ( this.originalValues.hasOwnProperty(key) === false ) {
  121. return;
  122. }
  123. var value = this.originalValues[key];
  124. // https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979
  125. // Forget the value immediately, it may change outside of
  126. // uBlock control.
  127. delete this.originalValues[key];
  128. // Original value was a default one
  129. if ( value === undefined ) {
  130. try {
  131. Services.prefs.getBranch(branch + '.').clearUserPref(setting);
  132. } catch (ex) {
  133. }
  134. return;
  135. }
  136. // Current value is same as original
  137. if ( this.getBool(branch, setting) === value ) {
  138. return;
  139. }
  140. // Reset to original value
  141. try {
  142. Services.prefs.getBranch(branch + '.').setBoolPref(setting, value);
  143. } catch (ex) {
  144. }
  145. },
  146. getBool: function(branch, setting) {
  147. try {
  148. return Services.prefs.getBranch(branch + '.').getBoolPref(setting);
  149. } catch (ex) {
  150. }
  151. return undefined;
  152. },
  153. setBool: function(branch, setting, value) {
  154. try {
  155. Services.prefs.getBranch(branch + '.').setBoolPref(setting, value);
  156. } catch (ex) {
  157. }
  158. },
  159. set: function(details) {
  160. var value;
  161. for ( var setting in details ) {
  162. if ( details.hasOwnProperty(setting) === false ) {
  163. continue;
  164. }
  165. switch ( setting ) {
  166. case 'prefetching':
  167. this.rememberOriginalValue('network', 'prefetch-next');
  168. value = !!details[setting];
  169. // https://github.com/gorhill/uBlock/issues/292
  170. // "true" means "do not disable", i.e. leave entry alone
  171. if ( value === true ) {
  172. this.clear('network', 'prefetch-next');
  173. } else {
  174. this.setBool('network', 'prefetch-next', false);
  175. }
  176. break;
  177. case 'hyperlinkAuditing':
  178. this.rememberOriginalValue('browser', 'send_pings');
  179. this.rememberOriginalValue('beacon', 'enabled');
  180. value = !!details[setting];
  181. // https://github.com/gorhill/uBlock/issues/292
  182. // "true" means "do not disable", i.e. leave entry alone
  183. if ( value === true ) {
  184. this.clear('browser', 'send_pings');
  185. this.clear('beacon', 'enabled');
  186. } else {
  187. this.setBool('browser', 'send_pings', false);
  188. this.setBool('beacon', 'enabled', false);
  189. }
  190. break;
  191. case 'webrtcIPAddress':
  192. this.rememberOriginalValue('media.peerconnection', 'enabled');
  193. value = !!details[setting];
  194. if ( value === true ) {
  195. this.clear('media.peerconnection', 'enabled');
  196. } else {
  197. this.setBool('media.peerconnection', 'enabled', false);
  198. }
  199. break;
  200. default:
  201. break;
  202. }
  203. }
  204. },
  205. restoreAll: function() {
  206. var pos;
  207. for ( var key in this.originalValues ) {
  208. if ( this.originalValues.hasOwnProperty(key) === false ) {
  209. continue;
  210. }
  211. pos = key.lastIndexOf('.');
  212. this.clear(key.slice(0, pos), key.slice(pos + 1));
  213. }
  214. }
  215. };
  216. cleanupTasks.push(vAPI.browserSettings.restoreAll.bind(vAPI.browserSettings));
  217. /******************************************************************************/
  218. // API matches that of chrome.storage.local:
  219. // https://developer.chrome.com/extensions/storage
  220. vAPI.storage = (function() {
  221. var db = null;
  222. var vacuumTimer = null;
  223. var close = function() {
  224. if ( vacuumTimer !== null ) {
  225. clearTimeout(vacuumTimer);
  226. vacuumTimer = null;
  227. }
  228. if ( db === null ) {
  229. return;
  230. }
  231. db.asyncClose();
  232. db = null;
  233. };
  234. var open = function() {
  235. if ( db !== null ) {
  236. return db;
  237. }
  238. // Create path
  239. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  240. path.append('extension-data');
  241. if ( !path.exists() ) {
  242. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  243. }
  244. if ( !path.isDirectory() ) {
  245. throw Error('Should be a directory...');
  246. }
  247. path.append(location.host + '.sqlite');
  248. // Open database
  249. try {
  250. db = Services.storage.openDatabase(path);
  251. if ( db.connectionReady === false ) {
  252. db.asyncClose();
  253. db = null;
  254. }
  255. } catch (ex) {
  256. }
  257. if ( db === null ) {
  258. return null;
  259. }
  260. // Database was opened, register cleanup task
  261. cleanupTasks.push(close);
  262. // Setup database
  263. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
  264. .executeAsync();
  265. if ( vacuum !== null ) {
  266. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  267. }
  268. return db;
  269. };
  270. // https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
  271. // Vacuum only once, and only while idle
  272. var vacuum = function() {
  273. vacuumTimer = null;
  274. if ( db === null ) {
  275. return;
  276. }
  277. var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
  278. .getService(Ci.nsIIdleService);
  279. if ( idleSvc.idleTime < 60000 ) {
  280. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  281. return;
  282. }
  283. db.createAsyncStatement('VACUUM').executeAsync();
  284. vacuum = null;
  285. };
  286. // Execute a query
  287. var runStatement = function(stmt, callback) {
  288. var result = {};
  289. stmt.executeAsync({
  290. handleResult: function(rows) {
  291. if ( !rows || typeof callback !== 'function' ) {
  292. return;
  293. }
  294. var row;
  295. while ( (row = rows.getNextRow()) ) {
  296. // we assume that there will be two columns, since we're
  297. // using it only for preferences
  298. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  299. }
  300. },
  301. handleCompletion: function(reason) {
  302. if ( typeof callback === 'function' && reason === 0 ) {
  303. callback(result);
  304. }
  305. },
  306. handleError: function(error) {
  307. console.error('SQLite error ', error.result, error.message);
  308. // Caller expects an answer regardless of failure.
  309. if ( typeof callback === 'function' ) {
  310. callback(null);
  311. }
  312. }
  313. });
  314. };
  315. var bindNames = function(stmt, names) {
  316. if ( Array.isArray(names) === false || names.length === 0 ) {
  317. return;
  318. }
  319. var params = stmt.newBindingParamsArray();
  320. var i = names.length, bp;
  321. while ( i-- ) {
  322. bp = params.newBindingParams();
  323. bp.bindByName('name', names[i]);
  324. params.addParams(bp);
  325. }
  326. stmt.bindParameters(params);
  327. };
  328. var clear = function(callback) {
  329. if ( open() === null ) {
  330. if ( typeof callback === 'function' ) {
  331. callback();
  332. }
  333. return;
  334. }
  335. runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
  336. };
  337. var getBytesInUse = function(keys, callback) {
  338. if ( typeof callback !== 'function' ) {
  339. return;
  340. }
  341. if ( open() === null ) {
  342. callback(0);
  343. return;
  344. }
  345. var stmt;
  346. if ( Array.isArray(keys) ) {
  347. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
  348. bindNames(keys);
  349. } else {
  350. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
  351. }
  352. runStatement(stmt, function(result) {
  353. callback(result.size);
  354. });
  355. };
  356. var read = function(details, callback) {
  357. if ( typeof callback !== 'function' ) {
  358. return;
  359. }
  360. var prepareResult = function(result) {
  361. var key;
  362. for ( key in result ) {
  363. if ( result.hasOwnProperty(key) === false ) {
  364. continue;
  365. }
  366. result[key] = JSON.parse(result[key]);
  367. }
  368. if ( typeof details === 'object' && details !== null ) {
  369. for ( key in details ) {
  370. if ( result.hasOwnProperty(key) === false ) {
  371. result[key] = details[key];
  372. }
  373. }
  374. }
  375. callback(result);
  376. };
  377. if ( open() === null ) {
  378. prepareResult({});
  379. return;
  380. }
  381. var names = [];
  382. if ( details !== null ) {
  383. if ( Array.isArray(details) ) {
  384. names = details;
  385. } else if ( typeof details === 'object' ) {
  386. names = Object.keys(details);
  387. } else {
  388. names = [details.toString()];
  389. }
  390. }
  391. var stmt;
  392. if ( names.length === 0 ) {
  393. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  394. } else {
  395. stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
  396. bindNames(stmt, names);
  397. }
  398. runStatement(stmt, prepareResult);
  399. };
  400. var remove = function(keys, callback) {
  401. if ( open() === null ) {
  402. if ( typeof callback === 'function' ) {
  403. callback();
  404. }
  405. return;
  406. }
  407. var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
  408. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  409. runStatement(stmt, callback);
  410. };
  411. var write = function(details, callback) {
  412. if ( open() === null ) {
  413. if ( typeof callback === 'function' ) {
  414. callback();
  415. }
  416. return;
  417. }
  418. var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
  419. var params = stmt.newBindingParamsArray(), bp;
  420. for ( var key in details ) {
  421. if ( details.hasOwnProperty(key) === false ) {
  422. continue;
  423. }
  424. bp = params.newBindingParams();
  425. bp.bindByName('name', key);
  426. bp.bindByName('value', JSON.stringify(details[key]));
  427. params.addParams(bp);
  428. }
  429. if ( params.length === 0 ) {
  430. return;
  431. }
  432. stmt.bindParameters(params);
  433. runStatement(stmt, callback);
  434. };
  435. // Export API
  436. var api = {
  437. QUOTA_BYTES: 100 * 1024 * 1024,
  438. clear: clear,
  439. get: read,
  440. getBytesInUse: getBytesInUse,
  441. remove: remove,
  442. set: write
  443. };
  444. return api;
  445. })();
  446. /******************************************************************************/
  447. var getTabBrowser = function(win) {
  448. return win.gBrowser || null;
  449. };
  450. /******************************************************************************/
  451. var getOwnerWindow = function(target) {
  452. if ( target.ownerDocument ) {
  453. return target.ownerDocument.defaultView;
  454. }
  455. return null;
  456. };
  457. /******************************************************************************/
  458. vAPI.isBehindTheSceneTabId = function(tabId) {
  459. return tabId.toString() === '-1';
  460. };
  461. vAPI.noTabId = '-1';
  462. /******************************************************************************/
  463. vAPI.tabs = {};
  464. /******************************************************************************/
  465. vAPI.tabs.registerListeners = function() {
  466. tabWatcher.start();
  467. };
  468. /******************************************************************************/
  469. vAPI.tabs.get = function(tabId, callback) {
  470. var browser;
  471. if ( tabId === null ) {
  472. browser = tabWatcher.currentBrowser();
  473. tabId = tabWatcher.tabIdFromTarget(browser);
  474. } else {
  475. browser = tabWatcher.browserFromTabId(tabId);
  476. }
  477. // For internal use
  478. if ( typeof callback !== 'function' ) {
  479. return browser;
  480. }
  481. if ( !browser ) {
  482. callback();
  483. return;
  484. }
  485. var win = getOwnerWindow(browser);
  486. var tabBrowser = getTabBrowser(win);
  487. var windows = this.getWindows();
  488. callback({
  489. id: tabId,
  490. index: tabWatcher.indexFromTarget(browser),
  491. windowId: windows.indexOf(win),
  492. active: browser === tabBrowser.selectedBrowser,
  493. url: browser.currentURI.asciiSpec,
  494. title: browser.contentTitle
  495. });
  496. };
  497. /******************************************************************************/
  498. vAPI.tabs.getAllSync = function(window) {
  499. var win, tab;
  500. var tabs = [];
  501. for ( win of this.getWindows() ) {
  502. if ( window && window !== win ) {
  503. continue;
  504. }
  505. var tabBrowser = getTabBrowser(win);
  506. if ( tabBrowser === null ) {
  507. continue;
  508. }
  509. for ( tab of tabBrowser.tabs ) {
  510. tabs.push(tab);
  511. }
  512. }
  513. return tabs;
  514. };
  515. /******************************************************************************/
  516. vAPI.tabs.getAll = function(callback) {
  517. var tabs = [], tab;
  518. for ( var browser of tabWatcher.browsers() ) {
  519. tab = tabWatcher.tabFromBrowser(browser);
  520. if ( tab === null ) {
  521. continue;
  522. }
  523. if ( tab.hasAttribute('pending') ) {
  524. continue;
  525. }
  526. tabs.push({
  527. id: tabWatcher.tabIdFromTarget(browser),
  528. url: browser.currentURI.asciiSpec
  529. });
  530. }
  531. callback(tabs);
  532. };
  533. /******************************************************************************/
  534. vAPI.tabs.getWindows = function() {
  535. var winumerator = Services.wm.getEnumerator('navigator:browser');
  536. var windows = [];
  537. while ( winumerator.hasMoreElements() ) {
  538. var win = winumerator.getNext();
  539. if ( !win.closed ) {
  540. windows.push(win);
  541. }
  542. }
  543. return windows;
  544. };
  545. /******************************************************************************/
  546. // properties of the details object:
  547. // url: 'URL', // the address that will be opened
  548. // tabId: 1, // the tab is used if set, instead of creating a new one
  549. // index: -1, // undefined: end of the list, -1: following tab, or after index
  550. // active: false, // opens the tab in background - true and undefined: foreground
  551. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  552. vAPI.tabs.open = function(details) {
  553. if ( !details.url ) {
  554. return null;
  555. }
  556. // extension pages
  557. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  558. details.url = vAPI.getURL(details.url);
  559. }
  560. var tab;
  561. if ( details.select ) {
  562. var URI = Services.io.newURI(details.url, null, null);
  563. for ( tab of this.getAllSync() ) {
  564. var browser = tabWatcher.browserFromTarget(tab);
  565. // Or simply .equals if we care about the fragment
  566. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  567. continue;
  568. }
  569. this.select(tab);
  570. // Update URL if fragment is different
  571. if ( URI.equals(browser.currentURI) === false ) {
  572. browser.loadURI(URI.asciiSpec);
  573. }
  574. return;
  575. }
  576. }
  577. if ( details.active === undefined ) {
  578. details.active = true;
  579. }
  580. if ( details.tabId ) {
  581. tab = tabWatcher.browserFromTabId(details.tabId);
  582. if ( tab ) {
  583. tabWatcher.browserFromTarget(tab).loadURI(details.url);
  584. return;
  585. }
  586. }
  587. var win = Services.wm.getMostRecentWindow('navigator:browser');
  588. var tabBrowser = getTabBrowser(win);
  589. // Open in a standalone window
  590. if ( details.popup ) {
  591. Services.ww.openWindow(
  592. self,
  593. details.url,
  594. null,
  595. 'menubar=no,toolbar=no,location=no,resizable=yes',
  596. null
  597. );
  598. return;
  599. }
  600. if ( details.index === -1 ) {
  601. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  602. }
  603. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  604. if ( details.index !== undefined ) {
  605. tabBrowser.moveTabTo(tab, details.index);
  606. }
  607. };
  608. /******************************************************************************/
  609. // Replace the URL of a tab. Noop if the tab does not exist.
  610. vAPI.tabs.replace = function(tabId, url) {
  611. var targetURL = url;
  612. // extension pages
  613. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  614. targetURL = vAPI.getURL(targetURL);
  615. }
  616. var browser = tabWatcher.browserFromTabId(tabId);
  617. if ( browser ) {
  618. browser.loadURI(targetURL);
  619. }
  620. };
  621. /******************************************************************************/
  622. vAPI.tabs._remove = function(tab, tabBrowser) {
  623. tabBrowser.removeTab(tab);
  624. };
  625. /******************************************************************************/
  626. vAPI.tabs.remove = function(tabId) {
  627. var browser = tabWatcher.browserFromTabId(tabId);
  628. if ( !browser ) {
  629. return;
  630. }
  631. var tab = tabWatcher.tabFromBrowser(browser);
  632. if ( !tab ) {
  633. return;
  634. }
  635. this._remove(tab, getTabBrowser(getOwnerWindow(browser)));
  636. };
  637. /******************************************************************************/
  638. vAPI.tabs.reload = function(tabId) {
  639. var browser = tabWatcher.browserFromTabId(tabId);
  640. if ( !browser ) {
  641. return;
  642. }
  643. browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
  644. };
  645. /******************************************************************************/
  646. vAPI.tabs.select = function(tab) {
  647. if ( typeof tab !== 'object' ) {
  648. tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
  649. }
  650. if ( !tab ) {
  651. return;
  652. }
  653. // https://github.com/gorhill/uBlock/issues/470
  654. var win = getOwnerWindow(tab);
  655. win.focus();
  656. var tabBrowser = getTabBrowser(win);
  657. tabBrowser.selectedTab = tab;
  658. };
  659. /******************************************************************************/
  660. vAPI.tabs.injectScript = function(tabId, details, callback) {
  661. var browser = tabWatcher.browserFromTabId(tabId);
  662. if ( !browser ) {
  663. return;
  664. }
  665. if ( typeof details.file !== 'string' ) {
  666. return;
  667. }
  668. details.file = vAPI.getURL(details.file);
  669. browser.messageManager.sendAsyncMessage(
  670. location.host + ':broadcast',
  671. JSON.stringify({
  672. broadcast: true,
  673. channelName: 'vAPI',
  674. msg: {
  675. cmd: 'injectScript',
  676. details: details
  677. }
  678. })
  679. );
  680. if ( typeof callback === 'function' ) {
  681. vAPI.setTimeout(callback, 13);
  682. }
  683. };
  684. /******************************************************************************/
  685. // Firefox:
  686. // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
  687. //
  688. // browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
  689. // ^ |
  690. // | |
  691. // +-------------------------------------------------------------------
  692. //
  693. // browser (browser)
  694. // contentTitle
  695. // currentURI
  696. // ownerDocument (XULDocument)
  697. // defaultView (ChromeWindow)
  698. // gBrowser (tabbrowser OR browser)
  699. // browsers (browser)
  700. // selectedBrowser
  701. // selectedTab
  702. // tabs (tab.tabbrowser-tab)
  703. //
  704. // Fennec: (what I figured so far)
  705. //
  706. // tab --> browser windows --> window --> BrowserApp --> tabs --+
  707. // ^ window |
  708. // | |
  709. // +---------------------------------------------------------------+
  710. //
  711. // tab
  712. // browser
  713. // [manual search to go back to tab from list of windows]
  714. var tabWatcher = (function() {
  715. // TODO: find out whether we need a janitor to take care of stale entries.
  716. var browserToTabIdMap = new Map();
  717. var tabIdToBrowserMap = new Map();
  718. var tabIdGenerator = 1;
  719. var indexFromBrowser = function(browser) {
  720. var win = getOwnerWindow(browser);
  721. if ( !win ) {
  722. return -1;
  723. }
  724. var tabbrowser = getTabBrowser(win);
  725. if ( !tabbrowser ) {
  726. return -1;
  727. }
  728. // This can happen, for example, the `view-source:` window, there is
  729. // no tabbrowser object, the browser object sits directly in the
  730. // window.
  731. if ( tabbrowser === browser ) {
  732. return 0;
  733. }
  734. // Fennec
  735. // https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/BrowserApp
  736. if ( vAPI.fennec ) {
  737. return tabbrowser.tabs.indexOf(tabbrowser.getTabForBrowser(browser));
  738. }
  739. return tabbrowser.browsers.indexOf(browser);
  740. };
  741. var indexFromTarget = function(target) {
  742. return indexFromBrowser(browserFromTarget(target));
  743. };
  744. var tabFromBrowser = function(browser) {
  745. var i = indexFromBrowser(browser);
  746. if ( i === -1 ) {
  747. return null;
  748. }
  749. var win = getOwnerWindow(browser);
  750. if ( !win ) {
  751. return null;
  752. }
  753. var tabbrowser = getTabBrowser(win);
  754. if ( !tabbrowser ) {
  755. return null;
  756. }
  757. if ( !tabbrowser.tabs || i >= tabbrowser.tabs.length ) {
  758. return null;
  759. }
  760. return tabbrowser.tabs[i];
  761. };
  762. var browserFromTarget = function(target) {
  763. if ( !target ) {
  764. return null;
  765. }
  766. if ( vAPI.fennec ) {
  767. if ( target.browser ) { // target is a tab
  768. target = target.browser;
  769. }
  770. } else if ( target.linkedPanel ) { // target is a tab
  771. target = target.linkedBrowser;
  772. }
  773. if ( target.localName !== 'browser' ) {
  774. return null;
  775. }
  776. return target;
  777. };
  778. var tabIdFromTarget = function(target) {
  779. var browser = browserFromTarget(target);
  780. if ( browser === null ) {
  781. return vAPI.noTabId;
  782. }
  783. var tabId = browserToTabIdMap.get(browser);
  784. if ( tabId === undefined ) {
  785. tabId = '' + tabIdGenerator++;
  786. browserToTabIdMap.set(browser, tabId);
  787. tabIdToBrowserMap.set(tabId, browser);
  788. }
  789. return tabId;
  790. };
  791. var browserFromTabId = function(tabId) {
  792. var browser = tabIdToBrowserMap.get(tabId);
  793. if ( browser === undefined ) {
  794. return null;
  795. }
  796. // Verify that the browser is still live
  797. if ( indexFromBrowser(browser) !== -1 ) {
  798. return browser;
  799. }
  800. removeBrowserEntry(tabId, browser);
  801. return null;
  802. };
  803. var currentBrowser = function() {
  804. var win = Services.wm.getMostRecentWindow('navigator:browser');
  805. // https://github.com/gorhill/uBlock/issues/399
  806. // getTabBrowser() can return null at browser launch time.
  807. var tabBrowser = getTabBrowser(win);
  808. if ( tabBrowser === null ) {
  809. return null;
  810. }
  811. return browserFromTarget(tabBrowser.selectedTab);
  812. };
  813. var removeBrowserEntry = function(tabId, browser) {
  814. if ( tabId && tabId !== vAPI.noTabId ) {
  815. vAPI.tabs.onClosed(tabId);
  816. delete vAPI.toolbarButton.tabs[tabId];
  817. tabIdToBrowserMap.delete(tabId);
  818. }
  819. if ( browser ) {
  820. browserToTabIdMap.delete(browser);
  821. }
  822. };
  823. // https://developer.mozilla.org/en-US/docs/Web/Events/TabOpen
  824. var onOpen = function({target}) {
  825. var tabId = tabIdFromTarget(target);
  826. var browser = browserFromTabId(tabId);
  827. vAPI.tabs.onNavigation({
  828. frameId: 0,
  829. tabId: tabId,
  830. url: browser.currentURI.asciiSpec,
  831. });
  832. };
  833. // https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
  834. var onShow = function({target}) {
  835. tabIdFromTarget(target);
  836. };
  837. // https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
  838. var onClose = function({target}) {
  839. // target is tab in Firefox, browser in Fennec
  840. var browser = browserFromTarget(target);
  841. var tabId = browserToTabIdMap.get(browser);
  842. removeBrowserEntry(tabId, browser);
  843. };
  844. // https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
  845. var onSelect = function({target}) {
  846. vAPI.setIcon(tabIdFromTarget(target), getOwnerWindow(target));
  847. };
  848. var locationChangedMessageName = location.host + ':locationChanged';
  849. var onLocationChanged = function(e) {
  850. var vapi = vAPI;
  851. var details = e.data;
  852. // Ignore notifications related to our popup
  853. if ( details.url.lastIndexOf(vapi.getURL('popup.html'), 0) === 0 ) {
  854. return;
  855. }
  856. var browser = e.target;
  857. var tabId = tabIdFromTarget(browser);
  858. if ( tabId === vapi.noTabId ) {
  859. return;
  860. }
  861. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  862. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  863. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  864. vapi.tabs.onUpdated(tabId, {url: details.url}, {
  865. frameId: 0,
  866. tabId: tabId,
  867. url: browser.currentURI.asciiSpec
  868. });
  869. return;
  870. }
  871. // https://github.com/chrisaljoudi/uBlock/issues/105
  872. // Allow any kind of pages
  873. vapi.tabs.onNavigation({
  874. frameId: 0,
  875. tabId: tabId,
  876. url: details.url,
  877. });
  878. };
  879. var attachToTabBrowser = function(window) {
  880. var tabBrowser = getTabBrowser(window);
  881. if ( !tabBrowser ) {
  882. return false;
  883. }
  884. var tabContainer = tabBrowser.tabContainer;
  885. if ( !tabContainer ) {
  886. return true;
  887. }
  888. vAPI.contextMenu.register(window.document);
  889. if ( typeof vAPI.toolbarButton.attachToNewWindow === 'function' ) {
  890. vAPI.toolbarButton.attachToNewWindow(window);
  891. }
  892. tabContainer.addEventListener('TabOpen', onOpen);
  893. tabContainer.addEventListener('TabShow', onShow);
  894. tabContainer.addEventListener('TabClose', onClose);
  895. tabContainer.addEventListener('TabSelect', onSelect);
  896. return true;
  897. };
  898. var onWindowLoad = function(ev) {
  899. if ( ev ) {
  900. this.removeEventListener(ev.type, onWindowLoad);
  901. }
  902. var wintype = this.document.documentElement.getAttribute('windowtype');
  903. if ( wintype !== 'navigator:browser' ) {
  904. return;
  905. }
  906. // On some platforms, the tab browser isn't immediately available,
  907. // try waiting a bit if this happens.
  908. var win = this;
  909. if ( attachToTabBrowser(win) === false ) {
  910. vAPI.setTimeout(attachToTabBrowser.bind(null, win), 250);
  911. }
  912. };
  913. var onWindowUnload = function() {
  914. vAPI.contextMenu.unregister(this.document);
  915. this.removeEventListener('DOMContentLoaded', onWindowLoad);
  916. var tabBrowser = getTabBrowser(this);
  917. if ( !tabBrowser ) {
  918. return;
  919. }
  920. // https://github.com/gorhill/uBlock/issues/574
  921. // To keep in mind: not all browser windows are tab containers.
  922. var tabContainer = tabBrowser.tabContainer;
  923. if ( tabContainer ) {
  924. tabContainer.removeEventListener('TabOpen', onOpen);
  925. tabContainer.removeEventListener('TabShow', onShow);
  926. tabContainer.removeEventListener('TabClose', onClose);
  927. tabContainer.removeEventListener('TabSelect', onSelect);
  928. }
  929. // https://github.com/gorhill/uBlock/issues/574
  930. // To keep in mind: not all windows are tab containers,
  931. // sometimes the window IS the tab.
  932. var tabs;
  933. if ( tabBrowser.tabs ) {
  934. tabs = tabBrowser.tabs;
  935. } else if ( tabBrowser.localName === 'browser' ) {
  936. tabs = [tabBrowser];
  937. } else {
  938. tabs = [];
  939. }
  940. var browser, URI, tabId;
  941. for ( var tab of tabs ) {
  942. browser = tabWatcher.browserFromTarget(tab);
  943. if ( browser === null ) {
  944. continue;
  945. }
  946. URI = browser.currentURI;
  947. // Close extension tabs
  948. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  949. vAPI.tabs._remove(tab, getTabBrowser(this));
  950. }
  951. browser = browserFromTarget(tab);
  952. tabId = browserToTabIdMap.get(browser);
  953. if ( tabId !== undefined ) {
  954. removeBrowserEntry(tabId, browser);
  955. tabIdToBrowserMap.delete(tabId);
  956. }
  957. browserToTabIdMap.delete(browser);
  958. }
  959. };
  960. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
  961. var windowWatcher = {
  962. observe: function(win, topic) {
  963. if ( topic === 'domwindowopened' ) {
  964. win.addEventListener('DOMContentLoaded', onWindowLoad);
  965. return;
  966. }
  967. if ( topic === 'domwindowclosed' ) {
  968. onWindowUnload.call(win);
  969. return;
  970. }
  971. }
  972. };
  973. // Initialize map with existing active tabs
  974. var start = function() {
  975. var tabBrowser, tab;
  976. for ( var win of vAPI.tabs.getWindows() ) {
  977. onWindowLoad.call(win);
  978. tabBrowser = getTabBrowser(win);
  979. if ( tabBrowser === null ) {
  980. continue;
  981. }
  982. for ( tab of tabBrowser.tabs ) {
  983. if ( vAPI.fennec || !tab.hasAttribute('pending') ) {
  984. tabIdFromTarget(tab);
  985. }
  986. }
  987. }
  988. vAPI.messaging.globalMessageManager.addMessageListener(
  989. locationChangedMessageName,
  990. onLocationChanged
  991. );
  992. Services.ww.registerNotification(windowWatcher);
  993. };
  994. var stop = function() {
  995. vAPI.messaging.globalMessageManager.removeMessageListener(
  996. locationChangedMessageName,
  997. onLocationChanged
  998. );
  999. Services.ww.unregisterNotification(windowWatcher);
  1000. for ( var win of vAPI.tabs.getWindows() ) {
  1001. onWindowUnload.call(win);
  1002. }
  1003. browserToTabIdMap.clear();
  1004. tabIdToBrowserMap.clear();
  1005. };
  1006. cleanupTasks.push(stop);
  1007. return {
  1008. browsers: function() { return browserToTabIdMap.keys(); },
  1009. browserFromTabId: browserFromTabId,
  1010. browserFromTarget: browserFromTarget,
  1011. currentBrowser: currentBrowser,
  1012. indexFromTarget: indexFromTarget,
  1013. start: start,
  1014. tabFromBrowser: tabFromBrowser,
  1015. tabIdFromTarget: tabIdFromTarget
  1016. };
  1017. })();
  1018. /******************************************************************************/
  1019. vAPI.setIcon = function(tabId, iconId, badge) {
  1020. // If badge is undefined, then setIcon was called from the TabSelect event
  1021. var win;
  1022. if ( badge === undefined ) {
  1023. win = iconId;
  1024. } else {
  1025. win = Services.wm.getMostRecentWindow('navigator:browser');
  1026. }
  1027. var curTabId = tabWatcher.tabIdFromTarget(getTabBrowser(win).selectedTab);
  1028. var tb = vAPI.toolbarButton;
  1029. // from 'TabSelect' event
  1030. if ( tabId === undefined ) {
  1031. tabId = curTabId;
  1032. } else if ( badge !== undefined ) {
  1033. tb.tabs[tabId] = { badge: badge, img: iconId };
  1034. }
  1035. if ( tabId === curTabId ) {
  1036. tb.updateState(win, tabId);
  1037. }
  1038. };
  1039. /******************************************************************************/
  1040. vAPI.messaging = {
  1041. get globalMessageManager() {
  1042. return Cc['@mozilla.org/globalmessagemanager;1']
  1043. .getService(Ci.nsIMessageListenerManager);
  1044. },
  1045. frameScript: vAPI.getURL('frameScript.js'),
  1046. listeners: {},
  1047. defaultHandler: null,
  1048. NOOPFUNC: function(){},
  1049. UNHANDLED: 'vAPI.messaging.notHandled'
  1050. };
  1051. /******************************************************************************/
  1052. vAPI.messaging.listen = function(listenerName, callback) {
  1053. this.listeners[listenerName] = callback;
  1054. };
  1055. /******************************************************************************/
  1056. vAPI.messaging.onMessage = function({target, data}) {
  1057. var messageManager = target.messageManager;
  1058. if ( !messageManager ) {
  1059. // Message came from a popup, and its message manager is not usable.
  1060. // So instead we broadcast to the parent window.
  1061. messageManager = getOwnerWindow(
  1062. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  1063. ).messageManager;
  1064. }
  1065. var channelNameRaw = data.channelName;
  1066. var pos = channelNameRaw.indexOf('|');
  1067. var channelName = channelNameRaw.slice(pos + 1);
  1068. var callback = vAPI.messaging.NOOPFUNC;
  1069. if ( data.requestId !== undefined ) {
  1070. callback = CallbackWrapper.factory(
  1071. messageManager,
  1072. channelName,
  1073. channelNameRaw.slice(0, pos),
  1074. data.requestId
  1075. ).callback;
  1076. }
  1077. var sender = {
  1078. tab: {
  1079. id: tabWatcher.tabIdFromTarget(target)
  1080. }
  1081. };
  1082. // Specific handler
  1083. var r = vAPI.messaging.UNHANDLED;
  1084. var listener = vAPI.messaging.listeners[channelName];
  1085. if ( typeof listener === 'function' ) {
  1086. r = listener(data.msg, sender, callback);
  1087. }
  1088. if ( r !== vAPI.messaging.UNHANDLED ) {
  1089. return;
  1090. }
  1091. // Default handler
  1092. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  1093. if ( r !== vAPI.messaging.UNHANDLED ) {
  1094. return;
  1095. }
  1096. console.error('uMatrix> messaging > unknown request: %o', data);
  1097. // Unhandled:
  1098. // Need to callback anyways in case caller expected an answer, or
  1099. // else there is a memory leak on caller's side
  1100. callback();
  1101. };
  1102. /******************************************************************************/
  1103. vAPI.messaging.setup = function(defaultHandler) {
  1104. // Already setup?
  1105. if ( this.defaultHandler !== null ) {
  1106. return;
  1107. }
  1108. if ( typeof defaultHandler !== 'function' ) {
  1109. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  1110. }
  1111. this.defaultHandler = defaultHandler;
  1112. this.globalMessageManager.addMessageListener(
  1113. location.host + ':background',
  1114. this.onMessage
  1115. );
  1116. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  1117. cleanupTasks.push(function() {
  1118. var gmm = vAPI.messaging.globalMessageManager;
  1119. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  1120. gmm.removeMessageListener(
  1121. location.host + ':background',
  1122. vAPI.messaging.onMessage
  1123. );
  1124. });
  1125. };
  1126. /******************************************************************************/
  1127. vAPI.messaging.broadcast = function(message) {
  1128. this.globalMessageManager.broadcastAsyncMessage(
  1129. location.host + ':broadcast',
  1130. JSON.stringify({broadcast: true, msg: message})
  1131. );
  1132. };
  1133. /******************************************************************************/
  1134. // This allows to avoid creating a closure for every single message which
  1135. // expects an answer. Having a closure created each time a message is processed
  1136. // has been always bothering me. Another benefit of the implementation here
  1137. // is to reuse the callback proxy object, so less memory churning.
  1138. //
  1139. // https://developers.google.com/speed/articles/optimizing-javascript
  1140. // "Creating a closure is significantly slower then creating an inner
  1141. // function without a closure, and much slower than reusing a static
  1142. // function"
  1143. //
  1144. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  1145. // "the dreaded 'uniformly slow code' case where every function takes 1%
  1146. // of CPU and you have to make one hundred separate performance optimizations
  1147. // to improve performance at all"
  1148. //
  1149. // http://jsperf.com/closure-no-closure/2
  1150. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  1151. this.callback = this.proxy.bind(this); // bind once
  1152. this.init(messageManager, channelName, listenerId, requestId);
  1153. };
  1154. CallbackWrapper.junkyard = [];
  1155. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  1156. var wrapper = CallbackWrapper.junkyard.pop();
  1157. if ( wrapper ) {
  1158. wrapper.init(messageManager, channelName, listenerId, requestId);
  1159. return wrapper;
  1160. }
  1161. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  1162. };
  1163. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  1164. this.messageManager = messageManager;
  1165. this.channelName = channelName;
  1166. this.listenerId = listenerId;
  1167. this.requestId = requestId;
  1168. };
  1169. CallbackWrapper.prototype.proxy = function(response) {
  1170. var message = JSON.stringify({
  1171. requestId: this.requestId,
  1172. channelName: this.channelName,
  1173. msg: response !== undefined ? response : null
  1174. });
  1175. if ( this.messageManager.sendAsyncMessage ) {
  1176. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1177. } else {
  1178. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1179. }
  1180. // Mark for reuse
  1181. this.messageManager =
  1182. this.channelName =
  1183. this.requestId =
  1184. this.listenerId = null;
  1185. CallbackWrapper.junkyard.push(this);
  1186. };
  1187. /******************************************************************************/
  1188. var httpRequestHeadersFactory = function(channel) {
  1189. var entry = httpRequestHeadersFactory.junkyard.pop();
  1190. if ( entry ) {
  1191. return entry.init(channel);
  1192. }
  1193. return new HTTPRequestHeaders(channel);
  1194. };
  1195. httpRequestHeadersFactory.junkyard = [];
  1196. var HTTPRequestHeaders = function(channel) {
  1197. this.init(channel);
  1198. };
  1199. HTTPRequestHeaders.prototype.init = function(channel) {
  1200. this.channel = channel;
  1201. return this;
  1202. };
  1203. HTTPRequestHeaders.prototype.dispose = function() {
  1204. this.channel = null;
  1205. httpRequestHeadersFactory.junkyard.push(this);
  1206. };
  1207. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1208. try {
  1209. return this.channel.getRequestHeader(name);
  1210. } catch (e) {
  1211. }
  1212. return '';
  1213. };
  1214. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1215. var oldValue = this.getHeader(name);
  1216. if ( newValue === oldValue ) {
  1217. return false;
  1218. }
  1219. if ( oldValue === '' && create !== true ) {
  1220. return false;
  1221. }
  1222. this.channel.setRequestHeader(name, newValue, false);
  1223. return true;
  1224. };
  1225. /******************************************************************************/
  1226. var httpObserver = {
  1227. classDescription: 'net-channel-event-sinks for ' + location.host,
  1228. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1229. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1230. REQDATAKEY: location.host + 'reqdata',
  1231. ABORT: Components.results.NS_BINDING_ABORTED,
  1232. ACCEPT: Components.results.NS_SUCCEEDED,
  1233. // Request types:
  1234. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1235. frameTypeMap: {
  1236. 6: 'main_frame',
  1237. 7: 'sub_frame'
  1238. },
  1239. typeMap: {
  1240. 1: 'other',
  1241. 2: 'script',
  1242. 3: 'image',
  1243. 4: 'stylesheet',
  1244. 5: 'object',
  1245. 6: 'main_frame',
  1246. 7: 'sub_frame',
  1247. 10: 'ping',
  1248. 11: 'xmlhttprequest',
  1249. 12: 'object',
  1250. 14: 'font',
  1251. 15: 'media',
  1252. 16: 'websocket',
  1253. 21: 'image'
  1254. },
  1255. mimeTypeMap: {
  1256. 'audio': 15,
  1257. 'video': 15
  1258. },
  1259. get componentRegistrar() {
  1260. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1261. },
  1262. get categoryManager() {
  1263. return Cc['@mozilla.org/categorymanager;1']
  1264. .getService(Ci.nsICategoryManager);
  1265. },
  1266. QueryInterface: (function() {
  1267. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1268. return XPCOMUtils.generateQI([
  1269. Ci.nsIFactory,
  1270. Ci.nsIObserver,
  1271. Ci.nsIChannelEventSink,
  1272. Ci.nsISupportsWeakReference
  1273. ]);
  1274. })(),
  1275. createInstance: function(outer, iid) {
  1276. if ( outer ) {
  1277. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1278. }
  1279. return this.QueryInterface(iid);
  1280. },
  1281. register: function() {
  1282. this.pendingRingBufferInit();
  1283. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1284. Services.obs.addObserver(this, 'http-on-opening-request', true);
  1285. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1286. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1287. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1288. // Guard against stale instances not having been unregistered
  1289. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1290. try {
  1291. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1292. } catch (ex) {
  1293. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1294. }
  1295. }
  1296. this.componentRegistrar.registerFactory(
  1297. this.classID,
  1298. this.classDescription,
  1299. this.contractID,
  1300. this
  1301. );
  1302. this.categoryManager.addCategoryEntry(
  1303. 'net-channel-event-sinks',
  1304. this.contractID,
  1305. this.contractID,
  1306. false,
  1307. true
  1308. );
  1309. },
  1310. unregister: function() {
  1311. Services.obs.removeObserver(this, 'http-on-opening-request');
  1312. Services.obs.removeObserver(this, 'http-on-modify-request');
  1313. Services.obs.removeObserver(this, 'http-on-examine-response');
  1314. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1315. this.componentRegistrar.unregisterFactory(this.classID, this);
  1316. this.categoryManager.deleteCategoryEntry(
  1317. 'net-channel-event-sinks',
  1318. this.contractID,
  1319. false
  1320. );
  1321. },
  1322. PendingRequest: function() {
  1323. this.rawType = 0;
  1324. this.tabId = 0;
  1325. this._key = ''; // key is url, from URI.spec
  1326. },
  1327. // If all work fine, this map should not grow indefinitely. It can have
  1328. // stale items in it, but these will be taken care of when entries in
  1329. // the ring buffer are overwritten.
  1330. pendingURLToIndex: new Map(),
  1331. pendingWritePointer: 0,
  1332. pendingRingBuffer: new Array(32),
  1333. pendingRingBufferInit: function() {
  1334. // Use and reuse pre-allocated PendingRequest objects = less memory
  1335. // churning.
  1336. var i = this.pendingRingBuffer.length;
  1337. while ( i-- ) {
  1338. this.pendingRingBuffer[i] = new this.PendingRequest();
  1339. }
  1340. },
  1341. createPendingRequest: function(url) {
  1342. var bucket;
  1343. var i = this.pendingWritePointer;
  1344. this.pendingWritePointer = i + 1 & 31;
  1345. var preq = this.pendingRingBuffer[i];
  1346. // Cleanup unserviced pending request
  1347. if ( preq._key !== '' ) {
  1348. bucket = this.pendingURLToIndex.get(preq._key);
  1349. if ( Array.isArray(bucket) ) {
  1350. // Assuming i in array
  1351. var pos = bucket.indexOf(i);
  1352. bucket.splice(pos, 1);
  1353. if ( bucket.length === 1 ) {
  1354. this.pendingURLToIndex.set(preq._key, bucket[0]);
  1355. }
  1356. } else if ( typeof bucket === 'number' ) {
  1357. // Assuming bucket === i
  1358. this.pendingURLToIndex.delete(preq._key);
  1359. }
  1360. }
  1361. // Would be much simpler if a url could not appear more than once.
  1362. bucket = this.pendingURLToIndex.get(url);
  1363. if ( bucket === undefined ) {
  1364. this.pendingURLToIndex.set(url, i);
  1365. } else if ( Array.isArray(bucket) ) {
  1366. bucket = bucket.push(i);
  1367. } else {
  1368. bucket = [bucket, i];
  1369. }
  1370. preq._key = url;
  1371. return preq;
  1372. },
  1373. lookupPendingRequest: function(url) {
  1374. var i = this.pendingURLToIndex.get(url);
  1375. if ( i === undefined ) {
  1376. return null;
  1377. }
  1378. if ( Array.isArray(i) ) {
  1379. var bucket = i;
  1380. i = bucket.shift();
  1381. if ( bucket.length === 1 ) {
  1382. this.pendingURLToIndex.set(url, bucket[0]);
  1383. }
  1384. } else {
  1385. this.pendingURLToIndex.delete(url);
  1386. }
  1387. var preq = this.pendingRingBuffer[i];
  1388. preq._key = ''; // mark as "serviced"
  1389. return preq;
  1390. },
  1391. handleRequest: function(channel, URI, tabId, rawType) {
  1392. var type = this.typeMap[rawType] || 'other';
  1393. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1394. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  1395. return false;
  1396. }
  1397. var result = onBeforeRequest.callback({
  1398. hostname: URI.asciiHost,
  1399. parentFrameId: type === 'main_frame' ? -1 : 0,
  1400. tabId: tabId,
  1401. type: type,
  1402. url: URI.asciiSpec
  1403. });
  1404. if ( typeof result !== 'object' ) {
  1405. return false;
  1406. }
  1407. channel.cancel(this.ABORT);
  1408. return true;
  1409. },
  1410. handleRequestHeaders: function(channel, URI, tabId, rawType) {
  1411. var type = this.typeMap[rawType] || 'other';
  1412. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1413. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  1414. return;
  1415. }
  1416. var requestHeaders = httpRequestHeadersFactory(channel);
  1417. onBeforeSendHeaders.callback({
  1418. hostname: URI.asciiHost,
  1419. parentFrameId: type === 'main_frame' ? -1 : 0,
  1420. requestHeaders: requestHeaders,
  1421. tabId: tabId,
  1422. type: type,
  1423. url: URI.asciiSpec
  1424. });
  1425. requestHeaders.dispose();
  1426. },
  1427. channelDataFromChannel: function(channel) {
  1428. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1429. try {
  1430. return channel.getProperty(this.REQDATAKEY);
  1431. } catch (ex) {
  1432. }
  1433. }
  1434. return null;
  1435. },
  1436. // https://github.com/gorhill/uMatrix/issues/165
  1437. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1438. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1439. // care about embedded frames topography.
  1440. // Also:
  1441. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1442. tabIdFromChannel: function(channel) {
  1443. var aWindow;
  1444. if ( channel.notificationCallbacks ) {
  1445. try {
  1446. var loadContext = channel
  1447. .notificationCallbacks
  1448. .getInterface(Ci.nsILoadContext);
  1449. if ( loadContext.topFrameElement ) {
  1450. return tabWatcher.tabIdFromTarget(loadContext.topFrameElement);
  1451. }
  1452. aWindow = loadContext.associatedWindow;
  1453. } catch (ex) {
  1454. //console.error(ex);
  1455. }
  1456. }
  1457. try {
  1458. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  1459. aWindow = channel
  1460. .loadGroup
  1461. .notificationCallbacks
  1462. .getInterface(Ci.nsILoadContext)
  1463. .associatedWindow;
  1464. }
  1465. if ( aWindow ) {
  1466. return tabWatcher.tabIdFromTarget(
  1467. aWindow
  1468. .getInterface(Ci.nsIWebNavigation)
  1469. .QueryInterface(Ci.nsIDocShell)
  1470. .rootTreeItem
  1471. .QueryInterface(Ci.nsIInterfaceRequestor)
  1472. .getInterface(Ci.nsIDOMWindow)
  1473. .gBrowser
  1474. .getBrowserForContentWindow(aWindow)
  1475. );
  1476. }
  1477. } catch (ex) {
  1478. //console.error(ex);
  1479. }
  1480. return vAPI.noTabId;
  1481. },
  1482. rawtypeFromContentType: function(channel) {
  1483. var mime = channel.contentType;
  1484. if ( !mime ) {
  1485. return 0;
  1486. }
  1487. var pos = mime.indexOf('/');
  1488. if ( pos === -1 ) {
  1489. pos = mime.length;
  1490. }
  1491. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1492. },
  1493. observe: function(channel, topic) {
  1494. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1495. return;
  1496. }
  1497. var URI = channel.URI;
  1498. var channelData;
  1499. if ( topic.lastIndexOf('http-on-examine-', 0) === 0 ) {
  1500. channelData = this.channelDataFromChannel(channel);
  1501. if ( channelData === null ) {
  1502. return;
  1503. }
  1504. var type = this.frameTypeMap[channelData[1]];
  1505. if ( !type ) {
  1506. return;
  1507. }
  1508. topic = 'Content-Security-Policy';
  1509. var result;
  1510. try {
  1511. result = channel.getResponseHeader(topic);
  1512. } catch (ex) {
  1513. result = null;
  1514. }
  1515. result = vAPI.net.onHeadersReceived.callback({
  1516. hostname: URI.asciiHost,
  1517. parentFrameId: type === 'main_frame' ? -1 : 0,
  1518. responseHeaders: result ? [{name: topic, value: result}] : [],
  1519. tabId: channelData[0],
  1520. type: type,
  1521. url: URI.asciiSpec
  1522. });
  1523. if ( result ) {
  1524. channel.setResponseHeader(
  1525. topic,
  1526. result.responseHeaders.pop().value,
  1527. true
  1528. );
  1529. }
  1530. return;
  1531. }
  1532. if ( topic === 'http-on-modify-request' ) {
  1533. channelData = this.channelDataFromChannel(channel);
  1534. if ( channelData === null ) {
  1535. return;
  1536. }
  1537. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1538. return;
  1539. }
  1540. // http-on-opening-request
  1541. var tabId;
  1542. var pendingRequest = this.lookupPendingRequest(URI.asciiSpec);
  1543. var rawType = 1;
  1544. var loadInfo = channel.loadInfo;
  1545. // https://github.com/gorhill/uMatrix/issues/390#issuecomment-155717004
  1546. if ( loadInfo ) {
  1547. rawType = loadInfo.externalContentPolicyType !== undefined ?
  1548. loadInfo.externalContentPolicyType :
  1549. loadInfo.contentPolicyType;
  1550. if ( !rawType ) {
  1551. rawType = 1;
  1552. }
  1553. }
  1554. if ( pendingRequest !== null ) {
  1555. tabId = pendingRequest.tabId;
  1556. // https://github.com/gorhill/uBlock/issues/654
  1557. // Use the request type from the HTTP observer point of view.
  1558. if ( rawType !== 1 ) {
  1559. pendingRequest.rawType = rawType;
  1560. } else {
  1561. rawType = pendingRequest.rawType;
  1562. }
  1563. } else {
  1564. tabId = this.tabIdFromChannel(channel);
  1565. }
  1566. if ( this.handleRequest(channel, URI, tabId, rawType) ) {
  1567. return;
  1568. }
  1569. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1570. return;
  1571. }
  1572. // Carry data for behind-the-scene redirects
  1573. channel.setProperty(this.REQDATAKEY, [tabId, rawType]);
  1574. },
  1575. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1576. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1577. var result = this.ACCEPT;
  1578. // If error thrown, the redirect will fail
  1579. try {
  1580. var URI = newChannel.URI;
  1581. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1582. return;
  1583. }
  1584. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1585. return;
  1586. }
  1587. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1588. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1589. result = this.ABORT;
  1590. return;
  1591. }
  1592. // Carry the data on in case of multiple redirects
  1593. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1594. newChannel.setProperty(this.REQDATAKEY, channelData);
  1595. }
  1596. } catch (ex) {
  1597. // console.error(ex);
  1598. } finally {
  1599. callback.onRedirectVerifyCallback(result);
  1600. }
  1601. }
  1602. };
  1603. /******************************************************************************/
  1604. vAPI.net = {};
  1605. /******************************************************************************/
  1606. vAPI.net.registerListeners = function() {
  1607. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1608. new Set(this.onBeforeRequest.types) :
  1609. null;
  1610. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1611. new Set(this.onBeforeSendHeaders.types) :
  1612. null;
  1613. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1614. var shouldLoadListener = function(e) {
  1615. var details = e.data;
  1616. var pendingReq = httpObserver.createPendingRequest(details.url);
  1617. pendingReq.rawType = details.rawType;
  1618. pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
  1619. };
  1620. // https://github.com/gorhill/uMatrix/issues/200
  1621. // We need this only for Firefox 34 and less: the tab id is derived from
  1622. // the origin of the message.
  1623. if ( !vAPI.modernFirefox ) {
  1624. vAPI.messaging.globalMessageManager.addMessageListener(
  1625. shouldLoadListenerMessageName,
  1626. shouldLoadListener
  1627. );
  1628. }
  1629. httpObserver.register();
  1630. cleanupTasks.push(function() {
  1631. if ( !vAPI.modernFirefox ) {
  1632. vAPI.messaging.globalMessageManager.removeMessageListener(
  1633. shouldLoadListenerMessageName,
  1634. shouldLoadListener
  1635. );
  1636. }
  1637. httpObserver.unregister();
  1638. });
  1639. };
  1640. /******************************************************************************/
  1641. /******************************************************************************/
  1642. vAPI.toolbarButton = {
  1643. id: location.host + '-button',
  1644. type: 'view',
  1645. viewId: location.host + '-panel',
  1646. label: vAPI.app.name,
  1647. tooltiptext: vAPI.app.name,
  1648. tabs: {/*tabId: {badge: 0, img: boolean}*/},
  1649. init: null,
  1650. codePath: ''
  1651. };
  1652. /******************************************************************************/
  1653. // Non-Fennec: common code paths.
  1654. (function() {
  1655. if ( vAPI.fennec ) {
  1656. return;
  1657. }
  1658. var tbb = vAPI.toolbarButton;
  1659. var popupCommittedWidth = 0;
  1660. var popupCommittedHeight = 0;
  1661. tbb.onViewShowing = function({target}) {
  1662. popupCommittedWidth = popupCommittedHeight = 0;
  1663. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1664. };
  1665. tbb.onViewHiding = function({target}) {
  1666. target.parentNode.style.maxWidth = '';
  1667. target.firstChild.setAttribute('src', 'about:blank');
  1668. };
  1669. tbb.updateState = function(win, tabId) {
  1670. var button = win.document.getElementById(this.id);
  1671. if ( !button ) {
  1672. return;
  1673. }
  1674. var icon = this.tabs[tabId];
  1675. button.setAttribute('badge', icon && icon.badge || '');
  1676. button.classList.toggle('off', !icon || !icon.img);
  1677. var iconId = icon && icon.img ? icon.img : 'off';
  1678. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1679. button.style.listStyleImage = icon;
  1680. };
  1681. tbb.populatePanel = function(doc, panel) {
  1682. panel.setAttribute('id', this.viewId);
  1683. var iframe = doc.createElement('iframe');
  1684. iframe.setAttribute('type', 'content');
  1685. panel.appendChild(iframe);
  1686. var toPx = function(pixels) {
  1687. return pixels.toString() + 'px';
  1688. };
  1689. var scrollBarWidth = 0;
  1690. var resizeTimer = null;
  1691. var resizePopupDelayed = function(attempts) {
  1692. if ( resizeTimer !== null ) {
  1693. return false;
  1694. }
  1695. // Sanity check
  1696. attempts = (attempts || 0) + 1;
  1697. if ( attempts > 1/*000*/ ) {
  1698. //console.error('uMatrix> resizePopupDelayed: giving up after too many attempts');
  1699. return false;
  1700. }
  1701. resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
  1702. return true;
  1703. };
  1704. var resizePopup = function(attempts) {
  1705. resizeTimer = null;
  1706. panel.parentNode.style.maxWidth = 'none';
  1707. var body = iframe.contentDocument.body;
  1708. // https://github.com/gorhill/uMatrix/issues/301
  1709. // Don't resize if committed size did not change.
  1710. if (
  1711. popupCommittedWidth === body.clientWidth &&
  1712. popupCommittedHeight === body.clientHeight
  1713. ) {
  1714. return;
  1715. }
  1716. // We set a limit for height
  1717. var height = Math.min(body.clientHeight, 600);
  1718. // https://github.com/chrisaljoudi/uBlock/issues/730
  1719. // Voodoo programming: this recipe works
  1720. panel.style.setProperty('height', toPx(height));
  1721. iframe.style.setProperty('height', toPx(height));
  1722. // Adjust width for presence/absence of vertical scroll bar which may
  1723. // have appeared as a result of last operation.
  1724. var contentWindow = iframe.contentWindow;
  1725. var width = body.clientWidth;
  1726. if ( contentWindow.scrollMaxY !== 0 ) {
  1727. width += scrollBarWidth;
  1728. }
  1729. panel.style.setProperty('width', toPx(width));
  1730. // scrollMaxX should always be zero once we know the scrollbar width
  1731. if ( contentWindow.scrollMaxX !== 0 ) {
  1732. scrollBarWidth = contentWindow.scrollMaxX;
  1733. width += scrollBarWidth;
  1734. panel.style.setProperty('width', toPx(width));
  1735. }
  1736. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1737. if ( resizePopupDelayed(attempts) ) {
  1738. return;
  1739. }
  1740. // resizePopupDelayed won't be called again, so commit
  1741. // dimentsions.
  1742. }
  1743. popupCommittedWidth = body.clientWidth;
  1744. popupCommittedHeight = body.clientHeight;
  1745. };
  1746. var onResizeRequested = function() {
  1747. var body = iframe.contentDocument.body;
  1748. if ( body.getAttribute('data-resize-popup') !== 'true' ) {
  1749. return;
  1750. }
  1751. body.removeAttribute('data-resize-popup');
  1752. resizePopupDelayed();
  1753. };
  1754. var onPopupReady = function() {
  1755. var win = this.contentWindow;
  1756. if ( !win || win.location.host !== location.host ) {
  1757. return;
  1758. }
  1759. if ( typeof tbb.onBeforePopupReady === 'function' ) {
  1760. tbb.onBeforePopupReady.call(this);
  1761. }
  1762. resizePopupDelayed();
  1763. var body = win.document.body;
  1764. body.removeAttribute('data-resize-popup');
  1765. var mutationObserver = new win.MutationObserver(onResizeRequested);
  1766. mutationObserver.observe(body, {
  1767. attributes: true,
  1768. attributeFilter: [ 'data-resize-popup' ]
  1769. });
  1770. };
  1771. iframe.addEventListener('load', onPopupReady, true);
  1772. };
  1773. })();
  1774. /******************************************************************************/
  1775. // Firefox 28 and less
  1776. (function() {
  1777. var tbb = vAPI.toolbarButton;
  1778. if ( tbb.init !== null ) {
  1779. return;
  1780. }
  1781. var CustomizableUI = null;
  1782. var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
  1783. if ( !forceLegacyToolbarButton ) {
  1784. try {
  1785. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1786. } catch (ex) {
  1787. }
  1788. }
  1789. if ( CustomizableUI !== null ) {
  1790. return;
  1791. }
  1792. tbb.codePath = 'legacy';
  1793. tbb.id = 'umatrix-legacy-button'; // NOTE: must match legacy-toolbar-button.css
  1794. tbb.viewId = tbb.id + '-panel';
  1795. var sss = null;
  1796. var styleSheetUri = null;
  1797. var addLegacyToolbarButton = function(window) {
  1798. var document = window.document;
  1799. var toolbox = document.getElementById('navigator-toolbox') || document.getElementById('mail-toolbox');
  1800. if ( !toolbox ) {
  1801. return;
  1802. }
  1803. // palette might take a little longer to appear on some platforms,
  1804. // give it a small delay and try again.
  1805. var palette = toolbox.palette;
  1806. if ( !palette ) {
  1807. vAPI.setTimeout(function() {
  1808. if ( toolbox.palette ) {
  1809. addLegacyToolbarButton(window);
  1810. }
  1811. }, 250);
  1812. return;
  1813. }
  1814. var toolbarButton = document.createElement('toolbarbutton');
  1815. toolbarButton.setAttribute('id', tbb.id);
  1816. // type = panel would be more accurate, but doesn't look as good
  1817. toolbarButton.setAttribute('type', 'menu');
  1818. toolbarButton.setAttribute('removable', 'true');
  1819. toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
  1820. toolbarButton.setAttribute('label', tbb.label);
  1821. toolbarButton.setAttribute('tooltiptext', tbb.label);
  1822. var toolbarButtonPanel = document.createElement('panel');
  1823. // NOTE: Setting level to parent breaks the popup for PaleMoon under
  1824. // linux (mouse pointer misaligned with content). For some reason.
  1825. // toolbarButtonPanel.setAttribute('level', 'parent');
  1826. tbb.populatePanel(document, toolbarButtonPanel);
  1827. toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
  1828. toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
  1829. toolbarButton.appendChild(toolbarButtonPanel);
  1830. palette.appendChild(toolbarButton);
  1831. tbb.closePopup = function() {
  1832. toolbarButtonPanel.hidePopup();
  1833. };
  1834. // No button yet so give it a default location. If forcing the button,
  1835. // just put in in the palette rather than on any specific toolbar (who
  1836. // knows what toolbars will be available or visible!)
  1837. var toolbar;
  1838. if ( !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  1839. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  1840. toolbar = document.getElementById('nav-bar');
  1841. if ( toolbar === null ) {
  1842. return;
  1843. }
  1844. // https://github.com/gorhill/uBlock/issues/264
  1845. // Find a child customizable palette, if any.
  1846. toolbar = toolbar.querySelector('.customization-target') || toolbar;
  1847. toolbar.appendChild(toolbarButton);
  1848. toolbar.setAttribute('currentset', toolbar.currentSet);
  1849. document.persist(toolbar.id, 'currentset');
  1850. return;
  1851. }
  1852. // Find the place to put the button
  1853. var toolbars = toolbox.externalToolbars.slice();
  1854. for ( var child of toolbox.children ) {
  1855. if ( child.localName === 'toolbar' ) {
  1856. toolbars.push(child);
  1857. }
  1858. }
  1859. for ( toolbar of toolbars ) {
  1860. var currentsetString = toolbar.getAttribute('currentset');
  1861. if ( !currentsetString ) {
  1862. continue;
  1863. }
  1864. var currentset = currentsetString.split(',');
  1865. var index = currentset.indexOf(tbb.id);
  1866. if ( index === -1 ) {
  1867. continue;
  1868. }
  1869. // Found our button on this toolbar - but where on it?
  1870. var before = null;
  1871. for ( var i = index + 1; i < currentset.length; i++ ) {
  1872. before = document.getElementById(currentset[i]);
  1873. if ( before === null ) {
  1874. continue;
  1875. }
  1876. toolbar.insertItem(tbb.id, before);
  1877. break;
  1878. }
  1879. if ( before === null ) {
  1880. toolbar.insertItem(tbb.id);
  1881. }
  1882. }
  1883. };
  1884. var onPopupCloseRequested = function({target}) {
  1885. if ( typeof tbb.closePopup === 'function' ) {
  1886. tbb.closePopup(target);
  1887. }
  1888. };
  1889. var shutdown = function() {
  1890. for ( var win of vAPI.tabs.getWindows() ) {
  1891. var toolbarButton = win.document.getElementById(tbb.id);
  1892. if ( toolbarButton ) {
  1893. toolbarButton.parentNode.removeChild(toolbarButton);
  1894. }
  1895. }
  1896. if ( sss === null ) {
  1897. return;
  1898. }
  1899. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  1900. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  1901. }
  1902. sss = null;
  1903. styleSheetUri = null;
  1904. vAPI.messaging.globalMessageManager.removeMessageListener(
  1905. location.host + ':closePopup',
  1906. onPopupCloseRequested
  1907. );
  1908. };
  1909. tbb.attachToNewWindow = function(win) {
  1910. addLegacyToolbarButton(win);
  1911. };
  1912. tbb.init = function() {
  1913. vAPI.messaging.globalMessageManager.addMessageListener(
  1914. location.host + ':closePopup',
  1915. onPopupCloseRequested
  1916. );
  1917. sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
  1918. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  1919. // Register global so it works in all windows, including palette
  1920. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  1921. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  1922. }
  1923. cleanupTasks.push(shutdown);
  1924. };
  1925. })();
  1926. /******************************************************************************/
  1927. // Firefox Australis < 36.
  1928. (function() {
  1929. var tbb = vAPI.toolbarButton;
  1930. if ( tbb.init !== null ) {
  1931. return;
  1932. }
  1933. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  1934. return null;
  1935. }
  1936. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  1937. return null;
  1938. }
  1939. var CustomizableUI = null;
  1940. try {
  1941. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1942. } catch (ex) {
  1943. }
  1944. if ( CustomizableUI === null ) {
  1945. return;
  1946. }
  1947. tbb.codePath = 'australis';
  1948. tbb.CustomizableUI = CustomizableUI;
  1949. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  1950. var styleURI = null;
  1951. var onPopupCloseRequested = function({target}) {
  1952. if ( typeof tbb.closePopup === 'function' ) {
  1953. tbb.closePopup(target);
  1954. }
  1955. };
  1956. var shutdown = function() {
  1957. CustomizableUI.destroyWidget(tbb.id);
  1958. for ( var win of vAPI.tabs.getWindows() ) {
  1959. var panel = win.document.getElementById(tbb.viewId);
  1960. panel.parentNode.removeChild(panel);
  1961. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1962. .getInterface(Ci.nsIDOMWindowUtils)
  1963. .removeSheet(styleURI, 1);
  1964. }
  1965. vAPI.messaging.globalMessageManager.removeMessageListener(
  1966. location.host + ':closePopup',
  1967. onPopupCloseRequested
  1968. );
  1969. };
  1970. tbb.onBeforeCreated = function(doc) {
  1971. var panel = doc.createElement('panelview');
  1972. this.populatePanel(doc, panel);
  1973. doc.getElementById('PanelUI-multiView').appendChild(panel);
  1974. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1975. .getInterface(Ci.nsIDOMWindowUtils)
  1976. .loadSheet(styleURI, 1);
  1977. };
  1978. tbb.onBeforePopupReady = function() {
  1979. // https://github.com/gorhill/uBlock/issues/83
  1980. // Add `portrait` class if width is constrained.
  1981. try {
  1982. this.contentDocument.body.classList.toggle(
  1983. 'portrait',
  1984. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  1985. );
  1986. } catch (ex) {
  1987. /* noop */
  1988. }
  1989. };
  1990. tbb.init = function() {
  1991. vAPI.messaging.globalMessageManager.addMessageListener(
  1992. location.host + ':closePopup',
  1993. onPopupCloseRequested
  1994. );
  1995. var style = [
  1996. '#' + this.id + '.off {',
  1997. 'list-style-image: url(',
  1998. vAPI.getURL('img/browsericons/icon19-off.png'),
  1999. ');',
  2000. '}',
  2001. '#' + this.id + ' {',
  2002. 'list-style-image: url(',
  2003. vAPI.getURL('img/browsericons/icon19.png'),
  2004. ');',
  2005. '}',
  2006. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2007. 'width: 160px;',
  2008. 'height: 290px;',
  2009. 'overflow: hidden !important;',
  2010. '}',
  2011. '#' + this.id + '[badge]:not([badge=""])::after {',
  2012. 'position: absolute;',
  2013. 'margin-left: -16px;',
  2014. 'margin-top: 3px;',
  2015. 'padding: 1px 2px;',
  2016. 'font-size: 9px;',
  2017. 'font-weight: bold;',
  2018. 'color: #fff;',
  2019. 'background: #000;',
  2020. 'content: attr(badge);',
  2021. '}'
  2022. ];
  2023. styleURI = Services.io.newURI(
  2024. 'data:text/css,' + encodeURIComponent(style.join('')),
  2025. null,
  2026. null
  2027. );
  2028. this.closePopup = function(tabBrowser) {
  2029. CustomizableUI.hidePanelForNode(
  2030. tabBrowser.ownerDocument.getElementById(this.viewId)
  2031. );
  2032. };
  2033. CustomizableUI.createWidget(this);
  2034. cleanupTasks.push(shutdown);
  2035. };
  2036. })();
  2037. /******************************************************************************/
  2038. // Firefox Australis >= 36.
  2039. (function() {
  2040. var tbb = vAPI.toolbarButton;
  2041. if ( tbb.init !== null ) {
  2042. return;
  2043. }
  2044. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  2045. return null;
  2046. }
  2047. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2048. return null;
  2049. }
  2050. var CustomizableUI = null;
  2051. try {
  2052. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2053. } catch (ex) {
  2054. }
  2055. if ( CustomizableUI === null ) {
  2056. return null;
  2057. }
  2058. tbb.codePath = 'australis';
  2059. tbb.CustomizableUI = CustomizableUI;
  2060. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2061. var CUIEvents = {};
  2062. var badgeCSSRules = [
  2063. 'background: #000',
  2064. 'color: #fff'
  2065. ].join(';');
  2066. var updateBadgeStyle = function() {
  2067. for ( var win of vAPI.tabs.getWindows() ) {
  2068. var button = win.document.getElementById(tbb.id);
  2069. if ( button === null ) {
  2070. continue;
  2071. }
  2072. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2073. button,
  2074. 'class',
  2075. 'toolbarbutton-badge'
  2076. );
  2077. if ( !badge ) {
  2078. continue;
  2079. }
  2080. badge.style.cssText = badgeCSSRules;
  2081. }
  2082. };
  2083. var updateBadge = function() {
  2084. var wId = tbb.id;
  2085. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2086. for ( var win of vAPI.tabs.getWindows() ) {
  2087. var button = win.document.getElementById(wId);
  2088. if ( button === null ) {
  2089. continue;
  2090. }
  2091. if ( buttonInPanel ) {
  2092. button.classList.remove('badged-button');
  2093. continue;
  2094. }
  2095. button.classList.add('badged-button');
  2096. }
  2097. if ( buttonInPanel ) {
  2098. return;
  2099. }
  2100. // Anonymous elements need some time to be reachable
  2101. vAPI.setTimeout(updateBadgeStyle, 250);
  2102. }.bind(CUIEvents);
  2103. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2104. CUIEvents.onCustomizeEnd = updateBadge;
  2105. CUIEvents.onWidgetAdded = updateBadge;
  2106. CUIEvents.onWidgetUnderflow = updateBadge;
  2107. var onPopupCloseRequested = function({target}) {
  2108. if ( typeof tbb.closePopup === 'function' ) {
  2109. tbb.closePopup(target);
  2110. }
  2111. };
  2112. var shutdown = function() {
  2113. CustomizableUI.removeListener(CUIEvents);
  2114. CustomizableUI.destroyWidget(tbb.id);
  2115. for ( var win of vAPI.tabs.getWindows() ) {
  2116. var panel = win.document.getElementById(tbb.viewId);
  2117. panel.parentNode.removeChild(panel);
  2118. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2119. .getInterface(Ci.nsIDOMWindowUtils)
  2120. .removeSheet(styleURI, 1);
  2121. }
  2122. vAPI.messaging.globalMessageManager.removeMessageListener(
  2123. location.host + ':closePopup',
  2124. onPopupCloseRequested
  2125. );
  2126. };
  2127. var styleURI = null;
  2128. tbb.onBeforeCreated = function(doc) {
  2129. var panel = doc.createElement('panelview');
  2130. this.populatePanel(doc, panel);
  2131. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2132. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2133. .getInterface(Ci.nsIDOMWindowUtils)
  2134. .loadSheet(styleURI, 1);
  2135. };
  2136. tbb.onCreated = function(button) {
  2137. button.setAttribute('badge', '');
  2138. vAPI.setTimeout(updateBadge, 250);
  2139. };
  2140. tbb.onBeforePopupReady = function() {
  2141. // https://github.com/gorhill/uBlock/issues/83
  2142. // Add `portrait` class if width is constrained.
  2143. try {
  2144. this.contentDocument.body.classList.toggle(
  2145. 'portrait',
  2146. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2147. );
  2148. } catch (ex) {
  2149. /* noop */
  2150. }
  2151. };
  2152. tbb.closePopup = function(tabBrowser) {
  2153. CustomizableUI.hidePanelForNode(
  2154. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2155. );
  2156. };
  2157. tbb.init = function() {
  2158. vAPI.messaging.globalMessageManager.addMessageListener(
  2159. location.host + ':closePopup',
  2160. onPopupCloseRequested
  2161. );
  2162. CustomizableUI.addListener(CUIEvents);
  2163. var style = [
  2164. '#' + this.id + '.off {',
  2165. 'list-style-image: url(',
  2166. vAPI.getURL('img/browsericons/icon19-off.png'),
  2167. ');',
  2168. '}',
  2169. '#' + this.id + ' {',
  2170. 'list-style-image: url(',
  2171. vAPI.getURL('img/browsericons/icon19-19.png'),
  2172. ');',
  2173. '}',
  2174. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2175. 'width: 160px;',
  2176. 'height: 290px;',
  2177. 'overflow: hidden !important;',
  2178. '}'
  2179. ];
  2180. styleURI = Services.io.newURI(
  2181. 'data:text/css,' + encodeURIComponent(style.join('')),
  2182. null,
  2183. null
  2184. );
  2185. CustomizableUI.createWidget(this);
  2186. cleanupTasks.push(shutdown);
  2187. };
  2188. })();
  2189. /******************************************************************************/
  2190. // No toolbar button.
  2191. (function() {
  2192. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2193. // button code is one single cleanup task regardless of platform.
  2194. if ( vAPI.toolbarButton.init === null ) {
  2195. cleanupTasks.push(function(){});
  2196. }
  2197. })();
  2198. /******************************************************************************/
  2199. if ( vAPI.toolbarButton.init !== null ) {
  2200. vAPI.toolbarButton.init();
  2201. }
  2202. /******************************************************************************/
  2203. /******************************************************************************/
  2204. vAPI.contextMenu = {
  2205. contextMap: {
  2206. frame: 'inFrame',
  2207. link: 'onLink',
  2208. image: 'onImage',
  2209. audio: 'onAudio',
  2210. video: 'onVideo',
  2211. editable: 'onEditableArea'
  2212. }
  2213. };
  2214. /******************************************************************************/
  2215. vAPI.contextMenu.displayMenuItem = function({target}) {
  2216. var doc = target.ownerDocument;
  2217. var gContextMenu = doc.defaultView.gContextMenu;
  2218. if ( !gContextMenu.browser ) {
  2219. return;
  2220. }
  2221. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2222. var currentURI = gContextMenu.browser.currentURI;
  2223. // https://github.com/chrisaljoudi/uBlock/issues/105
  2224. // TODO: Should the element picker works on any kind of pages?
  2225. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2226. menuitem.hidden = true;
  2227. return;
  2228. }
  2229. var ctx = vAPI.contextMenu.contexts;
  2230. if ( !ctx ) {
  2231. menuitem.hidden = false;
  2232. return;
  2233. }
  2234. var ctxMap = vAPI.contextMenu.contextMap;
  2235. for ( var context of ctx ) {
  2236. if (
  2237. context === 'page' &&
  2238. !gContextMenu.onLink &&
  2239. !gContextMenu.onImage &&
  2240. !gContextMenu.onEditableArea &&
  2241. !gContextMenu.inFrame &&
  2242. !gContextMenu.onVideo &&
  2243. !gContextMenu.onAudio
  2244. ) {
  2245. menuitem.hidden = false;
  2246. return;
  2247. }
  2248. if ( gContextMenu[ctxMap[context]] ) {
  2249. menuitem.hidden = false;
  2250. return;
  2251. }
  2252. }
  2253. menuitem.hidden = true;
  2254. };
  2255. /******************************************************************************/
  2256. vAPI.contextMenu.register = function(doc) {
  2257. if ( !this.menuItemId ) {
  2258. return;
  2259. }
  2260. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2261. var menuitem = doc.createElement('menuitem');
  2262. menuitem.setAttribute('id', this.menuItemId);
  2263. menuitem.setAttribute('label', this.menuLabel);
  2264. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2265. menuitem.setAttribute('class', 'menuitem-iconic');
  2266. menuitem.addEventListener('command', this.onCommand);
  2267. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2268. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2269. };
  2270. /******************************************************************************/
  2271. vAPI.contextMenu.unregister = function(doc) {
  2272. if ( !this.menuItemId ) {
  2273. return;
  2274. }
  2275. var menuitem = doc.getElementById(this.menuItemId);
  2276. if ( menuitem === null ) {
  2277. return;
  2278. }
  2279. var contextMenu = menuitem.parentNode;
  2280. menuitem.removeEventListener('command', this.onCommand);
  2281. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2282. contextMenu.removeChild(menuitem);
  2283. };
  2284. /******************************************************************************/
  2285. vAPI.contextMenu.create = function(details, callback) {
  2286. this.menuItemId = details.id;
  2287. this.menuLabel = details.title;
  2288. this.contexts = details.contexts;
  2289. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2290. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2291. } else {
  2292. // default in Chrome
  2293. this.contexts = ['page'];
  2294. }
  2295. this.onCommand = function() {
  2296. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2297. var details = {
  2298. menuItemId: this.id
  2299. };
  2300. if ( gContextMenu.inFrame ) {
  2301. details.tagName = 'iframe';
  2302. // Probably won't work with e10s
  2303. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2304. } else if ( gContextMenu.onImage ) {
  2305. details.tagName = 'img';
  2306. details.srcUrl = gContextMenu.mediaURL;
  2307. } else if ( gContextMenu.onAudio ) {
  2308. details.tagName = 'audio';
  2309. details.srcUrl = gContextMenu.mediaURL;
  2310. } else if ( gContextMenu.onVideo ) {
  2311. details.tagName = 'video';
  2312. details.srcUrl = gContextMenu.mediaURL;
  2313. } else if ( gContextMenu.onLink ) {
  2314. details.tagName = 'a';
  2315. details.linkUrl = gContextMenu.linkURL;
  2316. }
  2317. callback(details, {
  2318. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2319. url: gContextMenu.browser.currentURI.asciiSpec
  2320. });
  2321. };
  2322. for ( var win of vAPI.tabs.getWindows() ) {
  2323. this.register(win.document);
  2324. }
  2325. };
  2326. /******************************************************************************/
  2327. vAPI.contextMenu.remove = function() {
  2328. for ( var win of vAPI.tabs.getWindows() ) {
  2329. this.unregister(win.document);
  2330. }
  2331. this.menuItemId = null;
  2332. this.menuLabel = null;
  2333. this.contexts = null;
  2334. this.onCommand = null;
  2335. };
  2336. /******************************************************************************/
  2337. /******************************************************************************/
  2338. var optionsObserver = {
  2339. addonId: 'uMatrix@raymondhill.net',
  2340. register: function() {
  2341. Services.obs.addObserver(this, 'addon-options-displayed', false);
  2342. cleanupTasks.push(this.unregister.bind(this));
  2343. var browser = tabWatcher.currentBrowser();
  2344. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  2345. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  2346. }
  2347. },
  2348. unregister: function() {
  2349. Services.obs.removeObserver(this, 'addon-options-displayed');
  2350. },
  2351. setupOptionsButton: function(doc, id, page) {
  2352. var button = doc.getElementById(id);
  2353. if ( button === null ) {
  2354. return;
  2355. }
  2356. button.addEventListener('command', function() {
  2357. vAPI.tabs.open({ url: page, index: -1 });
  2358. });
  2359. button.label = vAPI.i18n(id);
  2360. },
  2361. observe: function(doc, topic, addonId) {
  2362. if ( addonId !== this.addonId ) {
  2363. return;
  2364. }
  2365. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  2366. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  2367. }
  2368. };
  2369. optionsObserver.register();
  2370. /******************************************************************************/
  2371. /******************************************************************************/
  2372. vAPI.lastError = function() {
  2373. return null;
  2374. };
  2375. /******************************************************************************/
  2376. /******************************************************************************/
  2377. // This is called only once, when everything has been loaded in memory after
  2378. // the extension was launched. It can be used to inject content scripts
  2379. // in already opened web pages, to remove whatever nuisance could make it to
  2380. // the web pages before uBlock was ready.
  2381. vAPI.onLoadAllCompleted = function() {
  2382. for ( var browser of tabWatcher.browsers() ) {
  2383. browser.messageManager.sendAsyncMessage(
  2384. location.host + '-load-completed'
  2385. );
  2386. }
  2387. };
  2388. /******************************************************************************/
  2389. /******************************************************************************/
  2390. // Likelihood is that we do not have to punycode: given punycode overhead,
  2391. // it's faster to check and skip than do it unconditionally all the time.
  2392. var punycodeHostname = punycode.toASCII;
  2393. var isNotASCII = /[^\x21-\x7F]/;
  2394. vAPI.punycodeHostname = function(hostname) {
  2395. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2396. };
  2397. vAPI.punycodeURL = function(url) {
  2398. if ( isNotASCII.test(url) ) {
  2399. return Services.io.newURI(url, null, null).asciiSpec;
  2400. }
  2401. return url;
  2402. };
  2403. /******************************************************************************/
  2404. /******************************************************************************/
  2405. vAPI.cloud = (function() {
  2406. var extensionBranchPath = 'extensions.' + location.host;
  2407. var cloudBranchPath = extensionBranchPath + '.cloudStorage';
  2408. // https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658
  2409. // We must use get/setComplexValue in order to properly handle strings
  2410. // with unicode characters.
  2411. var iss = Ci.nsISupportsString;
  2412. var argstr = Components.classes['@mozilla.org/supports-string;1']
  2413. .createInstance(iss);
  2414. var options = {
  2415. defaultDeviceName: '',
  2416. deviceName: ''
  2417. };
  2418. // User-supplied device name.
  2419. try {
  2420. options.deviceName = Services.prefs
  2421. .getBranch(extensionBranchPath + '.')
  2422. .getComplexValue('deviceName', iss)
  2423. .data;
  2424. } catch(ex) {
  2425. }
  2426. var getDefaultDeviceName = function() {
  2427. var name = '';
  2428. try {
  2429. name = Services.prefs
  2430. .getBranch('services.sync.client.')
  2431. .getComplexValue('name', iss)
  2432. .data;
  2433. } catch(ex) {
  2434. }
  2435. return name || window.navigator.platform || window.navigator.oscpu;
  2436. };
  2437. var start = function(dataKeys) {
  2438. var extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.');
  2439. var syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.');
  2440. // Mark config entries as syncable
  2441. argstr.data = '';
  2442. var dataKey;
  2443. for ( var i = 0; i < dataKeys.length; i++ ) {
  2444. dataKey = dataKeys[i];
  2445. if ( extensionBranch.prefHasUserValue('cloudStorage.' + dataKey) === false ) {
  2446. extensionBranch.setComplexValue('cloudStorage.' + dataKey, iss, argstr);
  2447. }
  2448. syncBranch.setBoolPref(cloudBranchPath + '.' + dataKey, true);
  2449. }
  2450. };
  2451. var push = function(datakey, data, callback) {
  2452. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2453. var bin = {
  2454. 'source': options.deviceName || getDefaultDeviceName(),
  2455. 'tstamp': Date.now(),
  2456. 'data': data,
  2457. 'size': 0
  2458. };
  2459. bin.size = JSON.stringify(bin).length;
  2460. argstr.data = JSON.stringify(bin);
  2461. branch.setComplexValue(datakey, iss, argstr);
  2462. if ( typeof callback === 'function' ) {
  2463. callback();
  2464. }
  2465. };
  2466. var pull = function(datakey, callback) {
  2467. var result = null;
  2468. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2469. try {
  2470. var json = branch.getComplexValue(datakey, iss).data;
  2471. if ( typeof json === 'string' ) {
  2472. result = JSON.parse(json);
  2473. }
  2474. } catch(ex) {
  2475. }
  2476. callback(result);
  2477. };
  2478. var getOptions = function(callback) {
  2479. if ( typeof callback !== 'function' ) {
  2480. return;
  2481. }
  2482. options.defaultDeviceName = getDefaultDeviceName();
  2483. callback(options);
  2484. };
  2485. var setOptions = function(details, callback) {
  2486. if ( typeof details !== 'object' || details === null ) {
  2487. return;
  2488. }
  2489. var branch = Services.prefs.getBranch(extensionBranchPath + '.');
  2490. if ( typeof details.deviceName === 'string' ) {
  2491. argstr.data = details.deviceName;
  2492. branch.setComplexValue('deviceName', iss, argstr);
  2493. options.deviceName = details.deviceName;
  2494. }
  2495. getOptions(callback);
  2496. };
  2497. return {
  2498. start: start,
  2499. push: push,
  2500. pull: pull,
  2501. getOptions: getOptions,
  2502. setOptions: setOptions
  2503. };
  2504. })();
  2505. /******************************************************************************/
  2506. /******************************************************************************/
  2507. vAPI.browserData = {};
  2508. /******************************************************************************/
  2509. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2510. vAPI.browserData.clearCache = function(callback) {
  2511. // PURGE_DISK_DATA_ONLY:1
  2512. // PURGE_DISK_ALL:2
  2513. // PURGE_EVERYTHING:3
  2514. // However I verified that not argument does clear the cache data.
  2515. Services.cache2.clear();
  2516. if ( typeof callback === 'function' ) {
  2517. callback();
  2518. }
  2519. };
  2520. /******************************************************************************/
  2521. vAPI.browserData.clearOrigin = function(/* domain */) {
  2522. // TODO
  2523. };
  2524. /******************************************************************************/
  2525. /******************************************************************************/
  2526. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2527. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2528. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2529. vAPI.cookies = {};
  2530. /******************************************************************************/
  2531. vAPI.cookies.CookieEntry = function(ffCookie) {
  2532. this.domain = ffCookie.host;
  2533. this.name = ffCookie.name;
  2534. this.path = ffCookie.path;
  2535. this.secure = ffCookie.isSecure === true;
  2536. this.session = ffCookie.expires === 0;
  2537. this.value = ffCookie.value;
  2538. };
  2539. /******************************************************************************/
  2540. vAPI.cookies.start = function() {
  2541. Services.obs.addObserver(this, 'cookie-changed', false);
  2542. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2543. cleanupTasks.push(this.stop.bind(this));
  2544. };
  2545. /******************************************************************************/
  2546. vAPI.cookies.stop = function() {
  2547. Services.obs.removeObserver(this, 'cookie-changed');
  2548. Services.obs.removeObserver(this, 'private-cookie-changed');
  2549. };
  2550. /******************************************************************************/
  2551. vAPI.cookies.observe = function(subject, topic, reason) {
  2552. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2553. // return;
  2554. //}
  2555. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  2556. return;
  2557. }
  2558. if ( typeof this.onChanged === 'function' ) {
  2559. this.onChanged(new this.CookieEntry(subject));
  2560. }
  2561. };
  2562. /******************************************************************************/
  2563. // Meant and expected to be asynchronous.
  2564. vAPI.cookies.getAll = function(callback) {
  2565. if ( typeof callback !== 'function' ) {
  2566. return;
  2567. }
  2568. var onAsync = function() {
  2569. var out = [];
  2570. var enumerator = Services.cookies.enumerator;
  2571. var ffcookie;
  2572. while ( enumerator.hasMoreElements() ) {
  2573. ffcookie = enumerator.getNext();
  2574. if ( ffcookie instanceof Ci.nsICookie ) {
  2575. out.push(new this.CookieEntry(ffcookie));
  2576. }
  2577. }
  2578. callback(out);
  2579. };
  2580. vAPI.setTimeout(onAsync.bind(this), 0);
  2581. };
  2582. /******************************************************************************/
  2583. vAPI.cookies.remove = function(details, callback) {
  2584. var uri = Services.io.newURI(details.url, null, null);
  2585. var cookies = Services.cookies;
  2586. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  2587. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  2588. if ( typeof callback === 'function' ) {
  2589. callback({
  2590. domain: uri.asciiHost,
  2591. name: details.name,
  2592. path: uri.path
  2593. });
  2594. }
  2595. };
  2596. /******************************************************************************/
  2597. /******************************************************************************/
  2598. })();
  2599. /******************************************************************************/