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.

1064 lines
34 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 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
9 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. uMatrix - a browser extension to block requests.
  3. Copyright (C) 2014-2017 The uBlock Origin authors
  4. Copyright (C) 2017 Raymond Hill
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see {http://www.gnu.org/licenses/}.
  15. Home: https://github.com/gorhill/uMatrix
  16. */
  17. /* global self, µMatrix */
  18. // For background page
  19. 'use strict';
  20. /******************************************************************************/
  21. (function() {
  22. /******************************************************************************/
  23. var vAPI = self.vAPI = self.vAPI || {};
  24. var chrome = self.chrome;
  25. var manifest = chrome.runtime.getManifest();
  26. vAPI.chrome = true;
  27. vAPI.webextFlavor = '';
  28. if (
  29. self.browser instanceof Object &&
  30. typeof self.browser.runtime.getBrowserInfo === 'function'
  31. ) {
  32. self.browser.runtime.getBrowserInfo().then(function(info) {
  33. vAPI.webextFlavor = info.vendor + '-' + info.name + '-' + info.version;
  34. });
  35. }
  36. var noopFunc = function(){};
  37. /******************************************************************************/
  38. // https://github.com/gorhill/uMatrix/issues/234
  39. // https://developer.chrome.com/extensions/privacy#property-network
  40. chrome.privacy.network.networkPredictionEnabled.set({
  41. value: false
  42. });
  43. /******************************************************************************/
  44. vAPI.app = {
  45. name: manifest.name,
  46. version: manifest.version
  47. };
  48. /******************************************************************************/
  49. vAPI.app.start = function() {
  50. };
  51. /******************************************************************************/
  52. vAPI.app.stop = function() {
  53. };
  54. /******************************************************************************/
  55. vAPI.app.restart = function() {
  56. chrome.runtime.reload();
  57. };
  58. /******************************************************************************/
  59. // chrome.storage.local.get(null, function(bin){ console.debug('%o', bin); });
  60. vAPI.storage = chrome.storage.local;
  61. vAPI.cacheStorage = chrome.storage.local;
  62. /******************************************************************************/
  63. vAPI.tabs = {};
  64. /******************************************************************************/
  65. vAPI.isBehindTheSceneTabId = function(tabId) {
  66. return tabId.toString() === '-1';
  67. };
  68. vAPI.noTabId = '-1';
  69. /******************************************************************************/
  70. vAPI.tabs.registerListeners = function() {
  71. var onNavigationClient = this.onNavigation || noopFunc;
  72. var onUpdatedClient = this.onUpdated || noopFunc;
  73. var onClosedClient = this.onClosed || noopFunc;
  74. // https://developer.chrome.com/extensions/webNavigation
  75. // [onCreatedNavigationTarget ->]
  76. // onBeforeNavigate ->
  77. // onCommitted ->
  78. // onDOMContentLoaded ->
  79. // onCompleted
  80. // The chrome.webRequest.onBeforeRequest() won't be called for everything
  81. // else than `http`/`https`. Thus, in such case, we will bind the tab as
  82. // early as possible in order to increase the likelihood of a context
  83. // properly setup if network requests are fired from within the tab.
  84. // Example: Chromium + case #6 at
  85. // http://raymondhill.net/ublock/popup.html
  86. var reGoodForWebRequestAPI = /^https?:\/\//;
  87. var onCreatedNavigationTarget = function(details) {
  88. //console.debug('onCreatedNavigationTarget: tab id %d = "%s"', details.tabId, details.url);
  89. if ( reGoodForWebRequestAPI.test(details.url) ) {
  90. return;
  91. }
  92. details.tabId = details.tabId.toString();
  93. onNavigationClient(details);
  94. };
  95. var onUpdated = function(tabId, changeInfo, tab) {
  96. tabId = tabId.toString();
  97. onUpdatedClient(tabId, changeInfo, tab);
  98. };
  99. var onCommitted = function(details) {
  100. // Important: do not call client if not top frame.
  101. if ( details.frameId !== 0 ) {
  102. return;
  103. }
  104. details.tabId = details.tabId.toString();
  105. onNavigationClient(details);
  106. //console.debug('onCommitted: tab id %d = "%s"', details.tabId, details.url);
  107. };
  108. var onClosed = function(tabId) {
  109. onClosedClient(tabId.toString());
  110. };
  111. chrome.webNavigation.onCreatedNavigationTarget.addListener(onCreatedNavigationTarget);
  112. chrome.webNavigation.onCommitted.addListener(onCommitted);
  113. chrome.tabs.onUpdated.addListener(onUpdated);
  114. chrome.tabs.onRemoved.addListener(onClosed);
  115. };
  116. /******************************************************************************/
  117. // tabId: null, // active tab
  118. vAPI.tabs.get = function(tabId, callback) {
  119. var onTabReady = function(tab) {
  120. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  121. if ( chrome.runtime.lastError ) {
  122. }
  123. if ( tab instanceof Object ) {
  124. tab.id = tab.id.toString();
  125. }
  126. callback(tab);
  127. };
  128. if ( tabId !== null ) {
  129. if ( typeof tabId === 'string' ) {
  130. tabId = parseInt(tabId, 10);
  131. }
  132. chrome.tabs.get(tabId, onTabReady);
  133. return;
  134. }
  135. var onTabReceived = function(tabs) {
  136. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  137. if ( chrome.runtime.lastError ) {
  138. }
  139. var tab = null;
  140. if ( Array.isArray(tabs) && tabs.length !== 0 ) {
  141. tab = tabs[0];
  142. tab.id = tab.id.toString();
  143. }
  144. callback(tab);
  145. };
  146. chrome.tabs.query({ active: true, currentWindow: true }, onTabReceived);
  147. };
  148. /******************************************************************************/
  149. vAPI.tabs.getAll = function(callback) {
  150. var onTabsReady = function(tabs) {
  151. if ( Array.isArray(tabs) ) {
  152. var i = tabs.length;
  153. while ( i-- ) {
  154. tabs[i].id = tabs[i].id.toString();
  155. }
  156. }
  157. callback(tabs);
  158. };
  159. chrome.tabs.query({ url: '<all_urls>' }, onTabsReady);
  160. };
  161. /******************************************************************************/
  162. // properties of the details object:
  163. // url: 'URL', // the address that will be opened
  164. // tabId: 1, // the tab is used if set, instead of creating a new one
  165. // index: -1, // undefined: end of the list, -1: following tab, or after index
  166. // active: false, // opens the tab in background - true and undefined: foreground
  167. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  168. vAPI.tabs.open = function(details) {
  169. var targetURL = details.url;
  170. if ( typeof targetURL !== 'string' || targetURL === '' ) {
  171. return null;
  172. }
  173. // extension pages
  174. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  175. targetURL = vAPI.getURL(targetURL);
  176. }
  177. // dealing with Chrome's asynchronous API
  178. var wrapper = function() {
  179. if ( details.active === undefined ) {
  180. details.active = true;
  181. }
  182. var subWrapper = function() {
  183. var _details = {
  184. url: targetURL,
  185. active: !!details.active
  186. };
  187. // Opening a tab from incognito window won't focus the window
  188. // in which the tab was opened
  189. var focusWindow = function(tab) {
  190. if ( tab.active ) {
  191. chrome.windows.update(tab.windowId, { focused: true });
  192. }
  193. };
  194. if ( !details.tabId ) {
  195. if ( details.index !== undefined ) {
  196. _details.index = details.index;
  197. }
  198. chrome.tabs.create(_details, focusWindow);
  199. return;
  200. }
  201. // update doesn't accept index, must use move
  202. chrome.tabs.update(parseInt(details.tabId, 10), _details, function(tab) {
  203. // if the tab doesn't exist
  204. if ( vAPI.lastError() ) {
  205. chrome.tabs.create(_details, focusWindow);
  206. } else if ( details.index !== undefined ) {
  207. chrome.tabs.move(tab.id, {index: details.index});
  208. }
  209. });
  210. };
  211. if ( details.index !== -1 ) {
  212. subWrapper();
  213. return;
  214. }
  215. vAPI.tabs.get(null, function(tab) {
  216. if ( tab ) {
  217. details.index = tab.index + 1;
  218. } else {
  219. delete details.index;
  220. }
  221. subWrapper();
  222. });
  223. };
  224. if ( !details.select ) {
  225. wrapper();
  226. return;
  227. }
  228. chrome.tabs.query({ url: targetURL }, function(tabs) {
  229. if ( chrome.runtime.lastError ) { /* noop */ }
  230. var tab = Array.isArray(tabs) && tabs[0];
  231. if ( tab ) {
  232. chrome.tabs.update(tab.id, { active: true }, function(tab) {
  233. chrome.windows.update(tab.windowId, { focused: true });
  234. });
  235. } else {
  236. wrapper();
  237. }
  238. });
  239. };
  240. /******************************************************************************/
  241. // Replace the URL of a tab. Noop if the tab does not exist.
  242. vAPI.tabs.replace = function(tabId, url) {
  243. var targetURL = url;
  244. // extension pages
  245. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  246. targetURL = vAPI.getURL(targetURL);
  247. }
  248. if ( typeof tabId !== 'number' ) {
  249. tabId = parseInt(tabId, 10);
  250. if ( isNaN(tabId) ) {
  251. return;
  252. }
  253. }
  254. chrome.tabs.update(tabId, { url: targetURL }, function() {
  255. // this prevent console error
  256. if ( chrome.runtime.lastError ) {
  257. return;
  258. }
  259. });
  260. };
  261. /******************************************************************************/
  262. vAPI.tabs.remove = function(tabId) {
  263. var onTabRemoved = function() {
  264. if ( vAPI.lastError() ) {
  265. }
  266. };
  267. chrome.tabs.remove(parseInt(tabId, 10), onTabRemoved);
  268. };
  269. /******************************************************************************/
  270. vAPI.tabs.reload = function(tabId, bypassCache) {
  271. if ( typeof tabId === 'string' ) {
  272. tabId = parseInt(tabId, 10);
  273. }
  274. if ( isNaN(tabId) ) {
  275. return;
  276. }
  277. chrome.tabs.reload(tabId, { bypassCache: bypassCache === true });
  278. };
  279. /******************************************************************************/
  280. vAPI.tabs.injectScript = function(tabId, details, callback) {
  281. var onScriptExecuted = function() {
  282. // https://code.google.com/p/chromium/issues/detail?id=410868#c8
  283. if ( chrome.runtime.lastError ) {
  284. }
  285. if ( typeof callback === 'function' ) {
  286. callback();
  287. }
  288. };
  289. if ( tabId ) {
  290. tabId = parseInt(tabId, 10);
  291. chrome.tabs.executeScript(tabId, details, onScriptExecuted);
  292. } else {
  293. chrome.tabs.executeScript(details, onScriptExecuted);
  294. }
  295. };
  296. /******************************************************************************/
  297. // Must read: https://code.google.com/p/chromium/issues/detail?id=410868#c8
  298. // https://github.com/chrisaljoudi/uBlock/issues/19
  299. // https://github.com/chrisaljoudi/uBlock/issues/207
  300. // Since we may be called asynchronously, the tab id may not exist
  301. // anymore, so this ensures it does still exist.
  302. vAPI.setIcon = function(tabId, iconId, badge) {
  303. tabId = parseInt(tabId, 10);
  304. if ( isNaN(tabId) || tabId <= 0 ) {
  305. return;
  306. }
  307. var onIconReady = function() {
  308. if ( vAPI.lastError() ) {
  309. return;
  310. }
  311. chrome.browserAction.setBadgeText({ tabId: tabId, text: badge });
  312. if ( badge !== '' ) {
  313. chrome.browserAction.setBadgeBackgroundColor({
  314. tabId: tabId,
  315. color: '#000'
  316. });
  317. }
  318. };
  319. var iconSelector = typeof iconId === 'number' ? iconId : 'off';
  320. var iconPaths = {
  321. '19': 'img/browsericons/icon19-' + iconSelector + '.png'/* ,
  322. '38': 'img/browsericons/icon38-' + iconSelector + '.png' */
  323. };
  324. chrome.browserAction.setIcon({ tabId: tabId, path: iconPaths }, onIconReady);
  325. };
  326. /******************************************************************************/
  327. /******************************************************************************/
  328. vAPI.messaging = {
  329. ports: {},
  330. listeners: {},
  331. defaultHandler: null,
  332. NOOPFUNC: noopFunc,
  333. UNHANDLED: 'vAPI.messaging.notHandled'
  334. };
  335. /******************************************************************************/
  336. vAPI.messaging.listen = function(listenerName, callback) {
  337. this.listeners[listenerName] = callback;
  338. };
  339. /******************************************************************************/
  340. vAPI.messaging.onPortMessage = function(request, port) {
  341. var callback = vAPI.messaging.NOOPFUNC;
  342. if ( request.requestId !== undefined ) {
  343. callback = CallbackWrapper.factory(port, request).callback;
  344. }
  345. // Specific handler
  346. var r = vAPI.messaging.UNHANDLED;
  347. var listener = vAPI.messaging.listeners[request.channelName];
  348. if ( typeof listener === 'function' ) {
  349. r = listener(request.msg, port.sender, callback);
  350. }
  351. if ( r !== vAPI.messaging.UNHANDLED ) {
  352. return;
  353. }
  354. // Default handler
  355. r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback);
  356. if ( r !== vAPI.messaging.UNHANDLED ) {
  357. return;
  358. }
  359. console.error('µMatrix> messaging > unknown request: %o', request);
  360. // Unhandled:
  361. // Need to callback anyways in case caller expected an answer, or
  362. // else there is a memory leak on caller's side
  363. callback();
  364. };
  365. /******************************************************************************/
  366. vAPI.messaging.onPortDisconnect = function(port) {
  367. port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect);
  368. port.onMessage.removeListener(vAPI.messaging.onPortMessage);
  369. delete vAPI.messaging.ports[port.name];
  370. };
  371. /******************************************************************************/
  372. vAPI.messaging.onPortConnect = function(port) {
  373. port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect);
  374. port.onMessage.addListener(vAPI.messaging.onPortMessage);
  375. vAPI.messaging.ports[port.name] = port;
  376. };
  377. /******************************************************************************/
  378. vAPI.messaging.setup = function(defaultHandler) {
  379. // Already setup?
  380. if ( this.defaultHandler !== null ) {
  381. return;
  382. }
  383. if ( typeof defaultHandler !== 'function' ) {
  384. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  385. }
  386. this.defaultHandler = defaultHandler;
  387. chrome.runtime.onConnect.addListener(this.onPortConnect);
  388. };
  389. /******************************************************************************/
  390. vAPI.messaging.broadcast = function(message) {
  391. var messageWrapper = {
  392. broadcast: true,
  393. msg: message
  394. };
  395. for ( var portName in this.ports ) {
  396. if ( this.ports.hasOwnProperty(portName) === false ) {
  397. continue;
  398. }
  399. this.ports[portName].postMessage(messageWrapper);
  400. }
  401. };
  402. /******************************************************************************/
  403. // This allows to avoid creating a closure for every single message which
  404. // expects an answer. Having a closure created each time a message is processed
  405. // has been always bothering me. Another benefit of the implementation here
  406. // is to reuse the callback proxy object, so less memory churning.
  407. //
  408. // https://developers.google.com/speed/articles/optimizing-javascript
  409. // "Creating a closure is significantly slower then creating an inner
  410. // function without a closure, and much slower than reusing a static
  411. // function"
  412. //
  413. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  414. // "the dreaded 'uniformly slow code' case where every function takes 1%
  415. // of CPU and you have to make one hundred separate performance optimizations
  416. // to improve performance at all"
  417. //
  418. // http://jsperf.com/closure-no-closure/2
  419. var CallbackWrapper = function(port, request) {
  420. // No need to bind every single time
  421. this.callback = this.proxy.bind(this);
  422. this.messaging = vAPI.messaging;
  423. this.init(port, request);
  424. };
  425. CallbackWrapper.junkyard = [];
  426. CallbackWrapper.factory = function(port, request) {
  427. var wrapper = CallbackWrapper.junkyard.pop();
  428. if ( wrapper ) {
  429. wrapper.init(port, request);
  430. return wrapper;
  431. }
  432. return new CallbackWrapper(port, request);
  433. };
  434. CallbackWrapper.prototype.init = function(port, request) {
  435. this.port = port;
  436. this.request = request;
  437. };
  438. CallbackWrapper.prototype.proxy = function(response) {
  439. // https://github.com/chrisaljoudi/uBlock/issues/383
  440. if ( this.messaging.ports.hasOwnProperty(this.port.name) ) {
  441. this.port.postMessage({
  442. requestId: this.request.requestId,
  443. channelName: this.request.channelName,
  444. msg: response !== undefined ? response : null
  445. });
  446. }
  447. // Mark for reuse
  448. this.port = this.request = null;
  449. CallbackWrapper.junkyard.push(this);
  450. };
  451. /******************************************************************************/
  452. /******************************************************************************/
  453. vAPI.net = {};
  454. /******************************************************************************/
  455. vAPI.net.registerListeners = function() {
  456. var µm = µMatrix,
  457. reNetworkURL = /^(?:https?|wss?):\/\//,
  458. httpRequestHeadersJunkyard = [];
  459. // Abstraction layer to deal with request headers
  460. // >>>>>>>>
  461. var httpRequestHeadersFactory = function(headers) {
  462. var entry = httpRequestHeadersJunkyard.pop();
  463. if ( entry ) {
  464. return entry.init(headers);
  465. }
  466. return new HTTPRequestHeaders(headers);
  467. };
  468. var HTTPRequestHeaders = function(headers) {
  469. this.init(headers);
  470. };
  471. HTTPRequestHeaders.prototype.init = function(headers) {
  472. this.modified = false;
  473. this.headers = headers;
  474. return this;
  475. };
  476. HTTPRequestHeaders.prototype.dispose = function() {
  477. var r = this.modified ? this.headers : null;
  478. this.headers = null;
  479. httpRequestHeadersJunkyard.push(this);
  480. return r;
  481. };
  482. HTTPRequestHeaders.prototype.getHeader = function(target) {
  483. var headers = this.headers;
  484. var header, name;
  485. var i = headers.length;
  486. while ( i-- ) {
  487. header = headers[i];
  488. name = header.name.toLowerCase();
  489. if ( name === target ) {
  490. return header.value;
  491. }
  492. }
  493. return '';
  494. };
  495. HTTPRequestHeaders.prototype.setHeader = function(target, value, create) {
  496. var headers = this.headers;
  497. var header, name;
  498. var i = headers.length;
  499. while ( i-- ) {
  500. header = headers[i];
  501. name = header.name.toLowerCase();
  502. if ( name === target ) {
  503. break;
  504. }
  505. }
  506. if ( i < 0 && !create ) { // Header not found, don't add it
  507. return false;
  508. }
  509. if ( i < 0 ) { // Header not found, add it
  510. headers.push({ name: target, value: value });
  511. } else if ( value === '' ) { // Header found, remove it
  512. headers.splice(i, 1);
  513. } else { // Header found, modify it
  514. header.value = value;
  515. }
  516. this.modified = true;
  517. return true;
  518. };
  519. // <<<<<<<<
  520. // End of: Abstraction layer to deal with request headers
  521. // Normalizing request types
  522. // >>>>>>>>
  523. var extToTypeMap = new Map([
  524. ['eot','font'],['otf','font'],['svg','font'],['ttf','font'],['woff','font'],['woff2','font'],
  525. ['mp3','media'],['mp4','media'],['webm','media'],
  526. ['gif','image'],['ico','image'],['jpeg','image'],['jpg','image'],['png','image'],['webp','image']
  527. ]);
  528. var normalizeRequestDetails = function(details) {
  529. details.tabId = details.tabId.toString();
  530. var type = details.type;
  531. if ( type === 'imageset' ) {
  532. details.type = 'image';
  533. return;
  534. }
  535. // The rest of the function code is to normalize request type
  536. if ( type !== 'other' ) {
  537. return;
  538. }
  539. if ( details.requestHeaders instanceof HTTPRequestHeaders ) {
  540. if ( details.requestHeaders.getHeader('ping-to') !== '' ) {
  541. details.type = 'ping';
  542. return;
  543. }
  544. }
  545. // Try to map known "extension" part of URL to request type.
  546. var path = µm.URI.pathFromURI(details.url),
  547. pos = path.indexOf('.', path.length - 6);
  548. if ( pos !== -1 && (type = extToTypeMap.get(path.slice(pos + 1))) ) {
  549. details.type = type;
  550. }
  551. };
  552. // <<<<<<<<
  553. // End of: Normalizing request types
  554. // Network event handlers
  555. // >>>>>>>>
  556. var onBeforeRequestClient = this.onBeforeRequest.callback;
  557. chrome.webRequest.onBeforeRequest.addListener(
  558. function(details) {
  559. if ( reNetworkURL.test(details.url) ) {
  560. normalizeRequestDetails(details);
  561. return onBeforeRequestClient(details);
  562. }
  563. },
  564. //function(details) {
  565. // quickProfiler.start('onBeforeRequest');
  566. // var r = onBeforeRequest(details);
  567. // quickProfiler.stop();
  568. // return r;
  569. //},
  570. {
  571. 'urls': this.onBeforeRequest.urls || [ '<all_urls>' ],
  572. 'types': this.onBeforeRequest.types || undefined
  573. },
  574. this.onBeforeRequest.extra
  575. );
  576. var onBeforeSendHeadersClient = this.onBeforeSendHeaders.callback;
  577. var onBeforeSendHeaders = function(details) {
  578. details.requestHeaders = httpRequestHeadersFactory(details.requestHeaders);
  579. normalizeRequestDetails(details);
  580. var result = onBeforeSendHeadersClient(details);
  581. if ( typeof result === 'object' ) {
  582. return result;
  583. }
  584. var modifiedHeaders = details.requestHeaders.dispose();
  585. if ( modifiedHeaders !== null ) {
  586. return { requestHeaders: modifiedHeaders };
  587. }
  588. };
  589. chrome.webRequest.onBeforeSendHeaders.addListener(
  590. onBeforeSendHeaders,
  591. {
  592. 'urls': this.onBeforeSendHeaders.urls || [ '<all_urls>' ],
  593. 'types': this.onBeforeSendHeaders.types || undefined
  594. },
  595. this.onBeforeSendHeaders.extra
  596. );
  597. var onHeadersReceivedClient = this.onHeadersReceived.callback;
  598. var onHeadersReceived = function(details) {
  599. normalizeRequestDetails(details);
  600. return onHeadersReceivedClient(details);
  601. };
  602. chrome.webRequest.onHeadersReceived.addListener(
  603. onHeadersReceived,
  604. {
  605. 'urls': this.onHeadersReceived.urls || [ '<all_urls>' ],
  606. 'types': this.onHeadersReceived.types || undefined
  607. },
  608. this.onHeadersReceived.extra
  609. );
  610. // <<<<<<<<
  611. // End of: Network event handlers
  612. };
  613. /******************************************************************************/
  614. /******************************************************************************/
  615. vAPI.contextMenu = {
  616. create: function(details, callback) {
  617. this.menuId = details.id;
  618. this.callback = callback;
  619. chrome.contextMenus.create(details);
  620. chrome.contextMenus.onClicked.addListener(this.callback);
  621. },
  622. remove: function() {
  623. chrome.contextMenus.onClicked.removeListener(this.callback);
  624. chrome.contextMenus.remove(this.menuId);
  625. }
  626. };
  627. /******************************************************************************/
  628. vAPI.lastError = function() {
  629. return chrome.runtime.lastError;
  630. };
  631. /******************************************************************************/
  632. /******************************************************************************/
  633. // This is called only once, when everything has been loaded in memory after
  634. // the extension was launched. It can be used to inject content scripts
  635. // in already opened web pages, to remove whatever nuisance could make it to
  636. // the web pages before uBlock was ready.
  637. vAPI.onLoadAllCompleted = function() {
  638. };
  639. /******************************************************************************/
  640. /******************************************************************************/
  641. vAPI.punycodeHostname = function(hostname) {
  642. return hostname;
  643. };
  644. vAPI.punycodeURL = function(url) {
  645. return url;
  646. };
  647. /******************************************************************************/
  648. /******************************************************************************/
  649. vAPI.browserData = {};
  650. /******************************************************************************/
  651. // https://developer.chrome.com/extensions/browsingData
  652. vAPI.browserData.clearCache = function(callback) {
  653. chrome.browsingData.removeCache({ since: 0 }, callback);
  654. };
  655. /******************************************************************************/
  656. // Not supported on Chromium
  657. vAPI.browserData.clearOrigin = function(domain, callback) {
  658. // unsupported on Chromium
  659. if ( typeof callback === 'function' ) {
  660. callback(undefined);
  661. }
  662. };
  663. /******************************************************************************/
  664. /******************************************************************************/
  665. // https://developer.chrome.com/extensions/cookies
  666. vAPI.cookies = {};
  667. /******************************************************************************/
  668. vAPI.cookies.start = function() {
  669. var reallyRemoved = {
  670. 'evicted': true,
  671. 'expired': true,
  672. 'explicit': true
  673. };
  674. var onChanged = function(changeInfo) {
  675. if ( changeInfo.removed ) {
  676. if ( reallyRemoved[changeInfo.cause] && typeof this.onRemoved === 'function' ) {
  677. this.onRemoved(changeInfo.cookie);
  678. }
  679. return;
  680. }
  681. if ( typeof this.onChanged === 'function' ) {
  682. this.onChanged(changeInfo.cookie);
  683. }
  684. };
  685. chrome.cookies.onChanged.addListener(onChanged.bind(this));
  686. };
  687. /******************************************************************************/
  688. vAPI.cookies.getAll = function(callback) {
  689. chrome.cookies.getAll({}, callback);
  690. };
  691. /******************************************************************************/
  692. vAPI.cookies.remove = function(details, callback) {
  693. chrome.cookies.remove(details, callback || noopFunc);
  694. };
  695. /******************************************************************************/
  696. /******************************************************************************/
  697. vAPI.cloud = (function() {
  698. // Not all platforms support `chrome.storage.sync`.
  699. if ( chrome.storage.sync instanceof Object === false ) {
  700. return;
  701. }
  702. var chunkCountPerFetch = 16; // Must be a power of 2
  703. // Mind chrome.storage.sync.MAX_ITEMS (512 at time of writing)
  704. var maxChunkCountPerItem = Math.floor(512 * 0.75) & ~(chunkCountPerFetch - 1);
  705. // Mind chrome.storage.sync.QUOTA_BYTES_PER_ITEM (8192 at time of writing)
  706. var maxChunkSize = chrome.storage.sync.QUOTA_BYTES_PER_ITEM || 8192;
  707. // Mind chrome.storage.sync.QUOTA_BYTES (128 kB at time of writing)
  708. // Firefox:
  709. // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/sync
  710. // > You can store up to 100KB of data using this API/
  711. var maxStorageSize = chrome.storage.sync.QUOTA_BYTES || 102400;
  712. // Flavor-specific handling needs to be done here. Reason: to allow time
  713. // for vAPI.webextFlavor to be properly set.
  714. // https://github.com/gorhill/uBlock/issues/3006
  715. // For Firefox, we will use a lower ratio to allow for more overhead for
  716. // the infrastructure. Unfortunately this leads to less usable space for
  717. // actual data, but all of this is provided for free by browser vendors,
  718. // so we need to accept and deal with these limitations.
  719. var initialize = function() {
  720. var ratio = vAPI.webextFlavor.startsWith('Mozilla-Firefox-') ? 0.6 : 0.75;
  721. maxChunkSize = Math.floor(maxChunkSize * ratio);
  722. initialize = function(){};
  723. };
  724. var options = {
  725. defaultDeviceName: window.navigator.platform,
  726. deviceName: vAPI.localStorage.getItem('deviceName') || ''
  727. };
  728. // This is used to find out a rough count of how many chunks exists:
  729. // We "poll" at specific index in order to get a rough idea of how
  730. // large is the stored string.
  731. // This allows reading a single item with only 2 sync operations -- a
  732. // good thing given chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_MINUTE
  733. // and chrome.storage.sync.MAX_WRITE_OPERATIONS_PER_HOUR.
  734. var getCoarseChunkCount = function(dataKey, callback) {
  735. var bin = {};
  736. for ( var i = 0; i < maxChunkCountPerItem; i += 16 ) {
  737. bin[dataKey + i.toString()] = '';
  738. }
  739. chrome.storage.sync.get(bin, function(bin) {
  740. if ( chrome.runtime.lastError ) {
  741. callback(0, chrome.runtime.lastError.message);
  742. return;
  743. }
  744. var chunkCount = 0;
  745. for ( var i = 0; i < maxChunkCountPerItem; i += 16 ) {
  746. if ( bin[dataKey + i.toString()] === '' ) {
  747. break;
  748. }
  749. chunkCount = i + 16;
  750. }
  751. callback(chunkCount);
  752. });
  753. };
  754. var deleteChunks = function(dataKey, start) {
  755. var keys = [];
  756. // No point in deleting more than:
  757. // - The max number of chunks per item
  758. // - The max number of chunks per storage limit
  759. var n = Math.min(
  760. maxChunkCountPerItem,
  761. Math.ceil(maxStorageSize / maxChunkSize)
  762. );
  763. for ( var i = start; i < n; i++ ) {
  764. keys.push(dataKey + i.toString());
  765. }
  766. chrome.storage.sync.remove(keys);
  767. };
  768. var start = function(/* dataKeys */) {
  769. };
  770. var push = function(dataKey, data, callback) {
  771. initialize();
  772. var bin = {
  773. 'source': options.deviceName || options.defaultDeviceName,
  774. 'tstamp': Date.now(),
  775. 'data': data,
  776. 'size': 0
  777. };
  778. bin.size = JSON.stringify(bin).length;
  779. var item = JSON.stringify(bin);
  780. // Chunkify taking into account QUOTA_BYTES_PER_ITEM:
  781. // https://developer.chrome.com/extensions/storage#property-sync
  782. // "The maximum size (in bytes) of each individual item in sync
  783. // "storage, as measured by the JSON stringification of its value
  784. // "plus its key length."
  785. bin = {};
  786. var chunkCount = Math.ceil(item.length / maxChunkSize);
  787. for ( var i = 0; i < chunkCount; i++ ) {
  788. bin[dataKey + i.toString()] = item.substr(i * maxChunkSize, maxChunkSize);
  789. }
  790. bin[dataKey + i.toString()] = ''; // Sentinel
  791. chrome.storage.sync.set(bin, function() {
  792. var errorStr;
  793. if ( chrome.runtime.lastError ) {
  794. errorStr = chrome.runtime.lastError.message;
  795. // https://github.com/gorhill/uBlock/issues/3006#issuecomment-332597677
  796. // - Delete all that was pushed in case of failure.
  797. chunkCount = 0;
  798. }
  799. callback(errorStr);
  800. // Remove potentially unused trailing chunks
  801. deleteChunks(dataKey, chunkCount);
  802. });
  803. };
  804. var pull = function(dataKey, callback) {
  805. initialize();
  806. var assembleChunks = function(bin) {
  807. if ( chrome.runtime.lastError ) {
  808. callback(null, chrome.runtime.lastError.message);
  809. return;
  810. }
  811. // Assemble chunks into a single string.
  812. var json = [], jsonSlice;
  813. var i = 0;
  814. for (;;) {
  815. jsonSlice = bin[dataKey + i.toString()];
  816. if ( jsonSlice === '' ) {
  817. break;
  818. }
  819. json.push(jsonSlice);
  820. i += 1;
  821. }
  822. var entry = null;
  823. try {
  824. entry = JSON.parse(json.join(''));
  825. } catch(ex) {
  826. }
  827. callback(entry);
  828. };
  829. var fetchChunks = function(coarseCount, errorStr) {
  830. if ( coarseCount === 0 || typeof errorStr === 'string' ) {
  831. callback(null, errorStr);
  832. return;
  833. }
  834. var bin = {};
  835. for ( var i = 0; i < coarseCount; i++ ) {
  836. bin[dataKey + i.toString()] = '';
  837. }
  838. chrome.storage.sync.get(bin, assembleChunks);
  839. };
  840. getCoarseChunkCount(dataKey, fetchChunks);
  841. };
  842. var getOptions = function(callback) {
  843. if ( typeof callback !== 'function' ) {
  844. return;
  845. }
  846. callback(options);
  847. };
  848. var setOptions = function(details, callback) {
  849. if ( typeof details !== 'object' || details === null ) {
  850. return;
  851. }
  852. if ( typeof details.deviceName === 'string' ) {
  853. vAPI.localStorage.setItem('deviceName', details.deviceName);
  854. options.deviceName = details.deviceName;
  855. }
  856. getOptions(callback);
  857. };
  858. return {
  859. start: start,
  860. push: push,
  861. pull: pull,
  862. getOptions: getOptions,
  863. setOptions: setOptions
  864. };
  865. })();
  866. /******************************************************************************/
  867. /******************************************************************************/
  868. })();
  869. /******************************************************************************/