forked from gorhill/httpswitchboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpagestats.js
More file actions
604 lines (491 loc) · 17.7 KB
/
pagestats.js
File metadata and controls
604 lines (491 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/*******************************************************************************
httpswitchboard - a Chromium browser extension to black/white list requests.
Copyright (C) 2013 Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/httpswitchboard
*/
/* global chrome, HTTPSB */
/*******************************************************************************
A PageRequestStore object is used to store net requests in two ways:
To record distinct net requests
To create a log of net requests
**/
HTTPSB.PageRequestStats = (function() {
/******************************************************************************/
// Caching useful global vars
var httpsb = HTTPSB;
var httpsburi = null;
/******************************************************************************/
// Hidden vars
var typeToCode = {
'main_frame' : 'a',
'sub_frame' : 'b',
'stylesheet' : 'c',
'script' : 'd',
'image' : 'e',
'object' : 'f',
'xmlhttprequest': 'g',
'other' : 'h',
'cookie' : 'i'
};
var codeToType = {
'a': 'main_frame',
'b': 'sub_frame',
'c': 'stylesheet',
'd': 'script',
'e': 'image',
'f': 'object',
'g': 'xmlhttprequest',
'h': 'other',
'i': 'cookie'
};
/******************************************************************************/
// It's just a dict-based "packer"
var stringPacker = {
codeGenerator: 1,
codeJunkyard: [],
mapStringToEntry: {},
mapCodeToString: {},
Entry: function(code) {
this.count = 0;
this.code = code;
},
remember: function(code) {
if ( code === '' ) {
return;
}
var s = this.mapCodeToString[code];
if ( s ) {
var entry = this.mapStringToEntry[s];
entry.count++;
}
},
forget: function(code) {
if ( code === '' ) {
return;
}
var s = this.mapCodeToString[code];
if ( s ) {
var entry = this.mapStringToEntry[s];
entry.count--;
if ( !entry.count ) {
// console.debug('stringPacker > releasing code "%s" (aka "%s")', code, s);
this.codeJunkyard.push(entry);
delete this.mapCodeToString[code];
delete this.mapStringToEntry[s];
}
}
},
pack: function(s) {
var entry = this.entryFromString(s);
if ( !entry ) {
return '';
}
return entry.code;
},
unpack: function(packed) {
return this.mapCodeToString[packed] || '';
},
stringify: function(code) {
if ( code <= 0xFFFF ) {
return String.fromCharCode(code);
}
return String.fromCharCode(code >>> 16) + String.fromCharCode(code & 0xFFFF);
},
entryFromString: function(s) {
if ( s === '' ) {
return null;
}
var entry = this.mapStringToEntry[s];
if ( !entry ) {
entry = this.codeJunkyard.pop();
if ( !entry ) {
entry = new this.Entry(this.stringify(this.codeGenerator++));
} else {
// console.debug('stringPacker > recycling code "%s" (aka "%s")', entry.code, s);
entry.count = 0;
}
this.mapStringToEntry[s] = entry;
this.mapCodeToString[entry.code] = s;
}
return entry;
}
};
/******************************************************************************/
var LogEntry = function() {
this.url = '';
this.type = '';
this.when = 0;
this.block = false;
this.reason = '';
};
var logEntryJunkyard = [];
LogEntry.prototype.dispose = function() {
// Let's not grab and hold onto too much memory..
if ( logEntryJunkyard.length < 200 ) {
logEntryJunkyard.push(this);
}
};
var logEntryFactory = function() {
var entry = logEntryJunkyard.pop();
if ( entry ) {
return entry;
}
return new LogEntry();
};
/******************************************************************************/
var PageRequestStats = function() {
this.requests = {};
this.ringBuffer = null;
this.ringBufferPointer = 0;
if ( !httpsburi ) {
httpsburi = httpsb.URI;
}
};
/******************************************************************************/
PageRequestStats.prototype.init = function() {
return this;
};
/******************************************************************************/
var pageRequestStoreJunkyard = [];
var pageRequestStoreFactory = function() {
var pageRequestStore = pageRequestStoreJunkyard.pop();
if ( pageRequestStore ) {
pageRequestStore.init();
} else {
pageRequestStore = new PageRequestStats();
}
pageRequestStore.resizeLogBuffer(httpsb.userSettings.maxLoggedRequests);
return pageRequestStore;
};
/******************************************************************************/
PageRequestStats.prototype.disposeOne = function(reqKey) {
if ( this.requests[reqKey] ) {
delete this.requests[reqKey];
forgetRequestKey(reqKey);
}
};
/******************************************************************************/
PageRequestStats.prototype.dispose = function() {
var requests = this.requests;
for ( var reqKey in requests ) {
if ( requests.hasOwnProperty(reqKey) === false ) {
continue;
}
stringPacker.forget(reqKey.slice(3));
delete requests[reqKey];
}
var i = this.ringBuffer.length;
var logEntry;
while ( i-- ) {
logEntry = this.ringBuffer[i];
if ( logEntry ) {
logEntry.dispose();
}
}
this.ringBuffer = [];
this.ringBufferPointer = 0;
if ( pageRequestStoreJunkyard.length < 8 ) {
pageRequestStoreJunkyard.push(this);
}
};
/******************************************************************************/
// Request key:
// index: 0123
// THHN
// ^^ ^
// || |
// || +--- short string code for hostname (dict-based)
// |+--- FNV32a hash of whole URI (irreversible)
// +--- single char code for type of request
var makeRequestKey = function(uri, reqType) {
// Ref: Given a URL, returns a unique 4-character long hash string
// Based on: FNV32a
// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-reference-source
// The rest is custom, suited for HTTPSB.
var hint = 0x811c9dc5;
var i = uri.length;
while ( i-- ) {
hint ^= uri.charCodeAt(i);
hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
hint >>>= 0;
}
var key = typeToCode[reqType] || 'z';
return key +
String.fromCharCode(hint >>> 16, hint & 0xFFFF) +
stringPacker.pack(httpsburi.hostnameFromURI(uri));
};
/******************************************************************************/
var rememberRequestKey = function(reqKey) {
stringPacker.remember(reqKey.slice(3));
};
var forgetRequestKey = function(reqKey) {
stringPacker.forget(reqKey.slice(3));
};
/******************************************************************************/
// Exported
var hostnameFromRequestKey = function(reqKey) {
return stringPacker.unpack(reqKey.slice(3));
};
PageRequestStats.prototype.hostnameFromRequestKey = hostnameFromRequestKey;
var typeFromRequestKey = function(reqKey) {
return codeToType[reqKey.charAt(0)];
};
PageRequestStats.prototype.typeFromRequestKey = typeFromRequestKey;
/******************************************************************************/
PageRequestStats.prototype.createEntryIfNotExists = function(url, type, block) {
var reqKey = makeRequestKey(url, type);
if ( this.requests[reqKey] ) {
return false;
}
rememberRequestKey(reqKey);
this.requests[reqKey] = Date.now();
return true;
};
/******************************************************************************/
PageRequestStats.prototype.resizeLogBuffer = function(size) {
if ( !this.ringBuffer ) {
this.ringBuffer = new Array(0);
this.ringBufferPointer = 0;
}
if ( size === this.ringBuffer.length ) {
return;
}
if ( !size ) {
this.ringBuffer = new Array(0);
this.ringBufferPointer = 0;
return;
}
var newBuffer = new Array(size);
var copySize = Math.min(size, this.ringBuffer.length);
var newBufferPointer = (copySize % size) | 0;
var isrc = this.ringBufferPointer;
var ides = newBufferPointer;
while ( copySize-- ) {
isrc--;
if ( isrc < 0 ) {
isrc = this.ringBuffer.length - 1;
}
ides--;
if ( ides < 0 ) {
ides = size - 1;
}
newBuffer[ides] = this.ringBuffer[isrc];
}
this.ringBuffer = newBuffer;
this.ringBufferPointer = newBufferPointer;
};
/******************************************************************************/
PageRequestStats.prototype.logRequest = function(url, type, block, reason) {
var buffer = this.ringBuffer;
var len = buffer.length;
if ( !len ) {
return;
}
var pointer = this.ringBufferPointer;
if ( !buffer[pointer] ) {
buffer[pointer] = logEntryFactory();
}
var logEntry = buffer[pointer];
logEntry.url = url;
logEntry.type = type;
logEntry.when = Date.now();
logEntry.block = block;
logEntry.reason = reason;
this.ringBufferPointer = ((pointer + 1) % len) | 0;
};
/******************************************************************************/
PageRequestStats.prototype.getLoggedRequests = function() {
var buffer = this.ringBuffer;
if ( !buffer.length ) {
return [];
}
// [0 - pointer] = most recent
// [pointer - length] = least recent
// thus, ascending order:
// [pointer - length] + [0 - pointer]
var pointer = this.ringBufferPointer;
return buffer.slice(pointer).concat(buffer.slice(0, pointer)).reverse();
};
/******************************************************************************/
PageRequestStats.prototype.getLoggedRequestEntry = function(reqURL, reqType) {
return this.requests[makeRequestKey(reqURL, reqType)];
};
/******************************************************************************/
PageRequestStats.prototype.getRequestKeys = function() {
return Object.keys(this.requests);
};
/******************************************************************************/
PageRequestStats.prototype.getRequestDict = function() {
return this.requests;
};
/******************************************************************************/
// Export
return {
factory: pageRequestStoreFactory,
hostnameFromRequestKey: hostnameFromRequestKey,
typeFromRequestKey: typeFromRequestKey
};
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
HTTPSB.PageStore = (function() {
/******************************************************************************/
var httpsb = HTTPSB;
var pageStoreJunkyard = [];
/******************************************************************************/
var pageStoreFactory = function(pageUrl) {
var entry = pageStoreJunkyard.pop();
if ( entry ) {
return entry.init(pageUrl);
}
return new PageStore(pageUrl);
};
/******************************************************************************/
function PageStore(pageUrl) {
this.pageUrl = '';
this.pageHostname = '';
this.pageDomain = '';
this.pageScriptBlocked = false;
this.thirdpartyScript = false;
this.requests = httpsb.PageRequestStats.factory();
this.domains = {};
this.state = {};
this.visible = false;
this.requestStats = new WebRequestStats();
this.distinctRequestCount = 0;
this.perLoadAllowedRequestCount = 0;
this.perLoadBlockedRequestCount = 0;
this.off = false;
this.abpBlockCount = 0;
this.init(pageUrl);
}
/******************************************************************************/
PageStore.prototype.init = function(pageUrl) {
this.pageUrl = pageUrl;
this.pageHostname = httpsb.URI.hostnameFromURI(pageUrl);
this.pageDomain = httpsb.URI.domainFromHostname(this.pageHostname);
this.pageScriptBlocked = false;
this.thirdpartyScript = false;
this.requests = httpsb.PageRequestStats.factory();
this.domains = {};
this.state = {};
this.requestStats.reset();
this.distinctRequestCount = 0;
this.perLoadAllowedRequestCount = 0;
this.perLoadBlockedRequestCount = 0;
this.abpBlockCount = 0;
return this;
};
/******************************************************************************/
PageStore.prototype.dispose = function() {
this.requests.dispose();
// rhill 2013-11-07: Even though at init time these are reset, I still
// need to release the memory taken by these, which can amount to
// sizeable enough chunks (especially requests, through the request URL
// used as a key).
this.pageUrl = '';
this.pageHostname = '';
this.pageDomain = '';
this.domains = {};
this.state = {};
if ( pageStoreJunkyard.length < 8 ) {
pageStoreJunkyard.push(this);
}
};
/******************************************************************************/
// rhill 2014-03-11: If `block` !== false, then block.toString() may return
// user legible information about the reason for the block.
PageStore.prototype.recordRequest = function(type, url, block, reason) {
// TODO: this makes no sense, I forgot why I put this here.
if ( !this ) {
// console.error('HTTP Switchboard> PageStore.recordRequest(): no pageStats');
return;
}
// rhill 2013-10-26: This needs to be called even if the request is
// already logged, since the request stats are cached for a while after
// the page is no longer visible in a browser tab.
httpsb.updateBadge(this.pageUrl);
// Count blocked/allowed requests
this.requestStats.record(type, block);
// https://github.com/gorhill/httpswitchboard/issues/306
// If it is recorded locally, record globally
httpsb.requestStats.record(type, block);
if ( block !== false ) {
this.perLoadBlockedRequestCount++;
} else {
this.perLoadAllowedRequestCount++;
}
this.requests.logRequest(url, type, block, reason);
if ( !this.requests.createEntryIfNotExists(url, type, block) ) {
return;
}
var hostname = httpsb.URI.hostnameFromURI(url);
// https://github.com/gorhill/httpswitchboard/issues/181
if ( type === 'script' && hostname !== this.pageHostname ) {
this.thirdpartyScript = true;
}
// rhill 2013-12-24: put blocked requests in dict on the fly, since
// doing it only at one point after the page has loaded completely will
// result in unnecessary reloads (because requests can be made *after*
// the page load has completed).
// https://github.com/gorhill/httpswitchboard/issues/98
// rhill 2014-03-12: disregard blocking operations which do not originate
// from matrix evaluation, or else this can cause a useless reload of the
// page if something important was blocked through ABP filtering.
if ( block !== false && reason === undefined ) {
this.state[type + '|' + hostname] = true;
}
this.distinctRequestCount++;
this.domains[hostname] = true;
httpsb.urlStatsChanged(this.pageUrl);
// console.debug("HTTP Switchboard> PageStore.recordRequest(): %o: %s @ %s", this, type, url);
};
/******************************************************************************/
// Update badge, incrementally
// rhill 2013-11-09: well this sucks, I can't update icon/badge
// incrementally, as chromium overwrite the icon at some point without
// notifying me, and this causes internal cached state to be out of sync.
PageStore.prototype.updateBadge = function(tabId) {
// Icon
var iconPath;
var total = this.perLoadAllowedRequestCount + this.perLoadBlockedRequestCount;
if ( total ) {
var squareSize = 19;
var greenSize = squareSize * Math.sqrt(this.perLoadAllowedRequestCount / total);
greenSize = greenSize < squareSize/2 ? Math.ceil(greenSize) : Math.floor(greenSize);
iconPath = 'img/browsericons/icon19-' + greenSize + '.png';
} else {
iconPath = 'img/browsericons/icon19.png';
}
chrome.browserAction.setIcon({ tabId: tabId, path: iconPath });
// Badge text & color
var badgeColor;
var badgeStr = httpsb.formatCount(this.distinctRequestCount);
var scopeKey = httpsb.temporaryScopeKeyFromPageURL(this.pageUrl);
if ( httpsb.isDomainScopeKey(scopeKey) ) {
badgeColor = '#24c';
} else if ( httpsb.isSiteScopeKey(scopeKey) ) {
badgeColor = '#48c';
} else {
badgeColor = '#000';
}
chrome.browserAction.setBadgeText({ tabId: tabId, text: badgeStr });
chrome.browserAction.setBadgeBackgroundColor({ tabId: tabId, color: badgeColor });
};
/******************************************************************************/
return {
factory: pageStoreFactory
};
})();
/******************************************************************************/