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.

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