This repository has been archived by the owner on May 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 89
/
ad_block_client.cc
1911 lines (1761 loc) · 64.3 KB
/
ad_block_client.cc
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <string.h>
#include <stdio.h>
#include "./protocol.h"
#include "./ad_block_client.h"
#include "./bad_fingerprint.h"
#include "./bad_fingerprints.h"
#include "./cosmetic_filter.h"
#include "./hashFn.h"
#include "./no_fingerprint_domain.h"
#include "BloomFilter.h"
#ifdef PERF_STATS
#include <iostream>
using std::cout;
using std::endl;
#endif
std::set<std::string> unknownOptions;
// Fast hash function applicable to 2 byte char checks
class HashFn2Byte : public HashFn {
public:
HashFn2Byte() : HashFn(0, false) {
}
uint64_t operator()(const char *input, int len,
unsigned char lastCharCode, uint64_t lastHash) override;
uint64_t operator()(const char *input, int len) override;
};
const int kMaxLineLength = 2048;
const int AdBlockClient::kFingerprintSize = 6;
static HashFn2Byte hashFn2Byte;
/**
* Finds the host within the passed in URL and returns its length
*/
const char * getUrlHost(const char *input, int *len) {
const char *p = input;
while (*p != '\0' && *p != ':') {
p++;
}
if (*p != '\0') {
p++;
while (*p != '\0' && *p == '/') {
p++;
}
}
const char *q = p;
while (*q != '\0') {
q++;
}
*len = findFirstSeparatorChar(p, q);
return p;
}
void AddFilterDomainsToHashSet(Filter* filter,
HashSet<NoFingerprintDomain> *hashSet) {
if (filter->domainList) {
char * filter_domain_list = filter->domainList;
int start_offset = 0;
int len = 0;
const char *p = filter_domain_list;
while (true) {
if (*p == '|' || *p == '\0') {
const char *domain = filter_domain_list + start_offset;
if (len > 0 && *domain != '~') {
char buffer[1024];
memset(buffer, 0, 1024);
memcpy(buffer, domain, len);
// cout << "Adding filter: " << buffer << endl;
hashSet->Add(NoFingerprintDomain(domain, len));
} else if (len > 0 && *domain == '~') {
char buffer[1024];
memset(buffer, 0, 1024);
memcpy(buffer, domain + 1, len - 1);
// cout << "Adding anti filter: " << buffer << endl;
hashSet->Add(NoFingerprintDomain(domain + 1, len - 1));
}
start_offset += len + 1;
len = -1;
}
if (*p == '\0') {
break;
}
p++;
len++;
}
}
}
inline bool isFingerprintChar(char c) {
return c != '|' && c != '*' && c != '^';
}
bool isBadFingerprint(const char *fingerprint, const char * fingerprintEnd) {
for (unsigned int i = 0; i < sizeof(badFingerprints)
/ sizeof(badFingerprints[0]); i++) {
if (!strncmp(badFingerprints[i], fingerprint,
fingerprintEnd - fingerprint)) {
return true;
}
}
return false;
}
bool hasBadSubstring(const char *fingerprint, const char * fingerprintEnd) {
for (unsigned int i = 0; i < sizeof(badSubstrings)
/ sizeof(badSubstrings[0]); i++) {
const char * p = strstr(fingerprint, badSubstrings[i]);
if (p && (p - fingerprint) + strlen(badSubstrings[i])
<= (unsigned int)(fingerprintEnd - fingerprint)) {
return true;
}
}
return false;
}
/**
* Obtains a fingerprint for the specified filter
*/
bool AdBlockClient::getFingerprint(char *buffer, const char *input) {
if (!input) {
return false;
}
int size = 0;
const char *p = input;
const char *start = input;
while (*p != '\0') {
if (!isFingerprintChar(*p)) {
size = 0;
p++;
start = p;
continue;
}
if (buffer) {
buffer[size] = *p;
}
if (hasBadSubstring(start, start + size + 1)) {
size = 0;
start++;
p = start;
continue;
}
size++;
if (size == kFingerprintSize) {
if (buffer) {
buffer[size] = '\0';
}
if (isBadFingerprint(start, start + size)) {
size = 0;
start++;
p = start;
continue;
}
return true;
}
p++;
}
if (buffer) {
buffer[0] = '\0';
}
return false;
}
bool AdBlockClient::getFingerprint(char *buffer, const Filter &f) {
if (f.filterType & FTRegex) {
// cout << "Get fingerprint for regex returning false; " << endl;
return false;
}
if (f.filterType & FTHostAnchored) {
if (AdBlockClient::getFingerprint(buffer, f.data + strlen(f.host))) {
return true;
}
}
bool b = AdBlockClient::getFingerprint(buffer, f.data);
// if (!b && f.data) {
// cout << "No fingerprint for: " << f.data << endl;
// }
return b;
}
// Separator chars are one of: :?/=^;
signed char separatorBuffer[32] = { 0, 0, 0, 0, 16, -128, 0, -92, 0, 0, 0, 64 };
bool isSeparatorChar(char c) {
return !!(separatorBuffer[(unsigned char)c / 8] & 1 << (unsigned char)c % 8);
}
int findFirstSeparatorChar(const char *input, const char *end) {
const char *p = input;
while (p != end) {
if (isSeparatorChar(*p)) {
return static_cast<int>(p - input);
}
p++;
}
return static_cast<int>(end - input);
}
void parseFilter(const char *input, Filter *f, BloomFilter *bloomFilter,
BloomFilter *exceptionBloomFilter,
HashSet<Filter> *hostAnchoredHashSet,
HashSet<Filter> *hostAnchoredExceptionHashSet,
HashSet<CosmeticFilter> *simpleCosmeticFilters,
bool preserveRules) {
const char *end = input;
while (*end != '\0') end++;
parseFilter(input, end, f, bloomFilter, exceptionBloomFilter,
hostAnchoredHashSet, hostAnchoredExceptionHashSet, simpleCosmeticFilters);
}
enum FilterParseState {
FPStart,
FPPastWhitespace,
FPOneBar,
FPOneAt,
FPData,
// Same as data but won't consider any special char handling like | or $
FPDataOnly
};
// Not currently multithreaded safe due to the static buffer named 'data'
void parseFilter(const char *input, const char *end, Filter *f,
BloomFilter *bloomFilter,
BloomFilter *exceptionBloomFilter,
HashSet<Filter> *hostAnchoredHashSet,
HashSet<Filter> *hostAnchoredExceptionHashSet,
HashSet<CosmeticFilter> *simpleCosmeticFilters,
bool preserveRules) {
FilterParseState parseState = FPStart;
const char *p = input;
const char *filterRuleStart = p;
const char *filterRuleEndPos = p;
char data[kMaxLineLength];
memset(data, 0, sizeof data);
int i = 0;
bool earlyBreak = false;
while (p != end && !earlyBreak) {
// Check for the filter being too long
if ((p - input) >= kMaxLineLength - 1) {
return;
}
if (parseState != FPDataOnly) {
if (parseState == FPOneBar && *p != '|') {
parseState = FPData;
f->filterType = static_cast<FilterType>(f->filterType | FTLeftAnchored);
}
switch (*p) {
case '|':
if (parseState == FPStart || parseState == FPPastWhitespace) {
parseState = FPOneBar;
filterRuleEndPos++;
p++;
continue;
} else if (parseState == FPOneBar) {
parseState = FPOneBar;
f->filterType =
static_cast<FilterType>(f->filterType | FTHostAnchored);
parseState = FPData;
filterRuleEndPos++;
p++;
int len = findFirstSeparatorChar(p, end);
// It's possible we have a host anchored filter
// which also has a right anchored filter.
if (len > 0 && p[len - 1] == '|') {
len--;
}
f->host = new char[len + 1];
f->host[len] = '\0';
memcpy(f->host, p, len);
if ((*(p + len) == '^' && (*(p + len + 1) == '\0'
|| *(p + len + 1) == '$' || isEndOfLine(*(p + len + 1)))) ||
*(p + len) == '\0' || *(p + len) == '$' ||
isEndOfLine(*(p + len))) {
f->filterType =
static_cast<FilterType>(f->filterType | FTHostOnly);
}
continue;
} else {
f->filterType =
static_cast<FilterType>(f->filterType | FTRightAnchored);
parseState = FPData;
filterRuleEndPos++;
p++;
continue;
}
break;
case '@':
if (parseState == FPStart || parseState == FPPastWhitespace) {
parseState = FPOneAt;
filterRuleEndPos++;
p++;
continue;
} else if (parseState == FPOneAt) {
parseState = FPOneBar;
f->filterType = FTException;
parseState = FPPastWhitespace;
filterRuleEndPos++;
p++;
continue;
}
break;
case '!':
case '[':
if (parseState == FPStart || parseState == FPPastWhitespace) {
f->filterType = FTComment;
// We don't care about comments right now
return;
}
break;
case '\r':
case '\n':
case '\t':
case ' ':
// Skip leading whitespace
if (parseState == FPStart) {
filterRuleStart++;
filterRuleEndPos++;
p++;
continue;
}
break;
case '/': {
const size_t inputLen = end - input;
if (parseState == FPStart || parseState == FPPastWhitespace) {
if (input[inputLen - 1] == '/' && inputLen > 1) {
// Just copy out the whole regex and return early
int len = static_cast<int>(inputLen) - i - 1;
f->data = new char[len];
f->data[len - 1] = '\0';
memcpy(f->data, input + i + 1, len - 1);
if (preserveRules) {
f->ruleDefinition = new char[len];
f->ruleDefinition[len - 1] = '\0';
memcpy(f->ruleDefinition, input + i + 1, len - 1);
}
f->filterType = FTRegex;
return;
} else {
parseState = FPData;
}
}
break;
}
case '$':
// Handle adguard HTML filtering rules syntax
// e.g. example.org$$script[data-src="banner"]
// see https://kb.adguard.com/en/general/how-to-create-your-own-ad-filters#html-filtering-rules-syntax-1
if (*(p+1) == '$') {
if (i != 0) {
f->domainList = new char[i + 1];
memcpy(f->domainList, data, i + 1);
i = 0;
}
parseState = FPDataOnly;
f->filterType = FTHTMLFiltering;
p += 2;
filterRuleEndPos += 2;
continue;
}
while (*filterRuleEndPos != '\0' && !isEndOfLine(*filterRuleEndPos)) {
filterRuleEndPos++;
}
f->parseOptions(p + 1);
earlyBreak = true;
continue;
case '#':
// ublock uses some comments of the form #[space]
if (parseState == FPStart || parseState == FPPastWhitespace) {
if (*(p+1) == ' ') {
f->filterType = FTComment;
// We don't care about comments right now
return;
}
}
if (*(p+1) == '#' || *(p+1) == '@') {
if (i != 0) {
f->domainList = new char[i + 1];
memcpy(f->domainList, data, i + 1);
i = 0;
}
parseState = FPDataOnly;
if (*(p+1) == '#') {
f->filterType = FTElementHiding;
} else {
f->filterType = FTElementHidingException;
}
p += 2;
continue;
}
// Copied from default label to avoid warning (unannotated
// fall-through between switch labels)
parseState = FPData;
break;
default:
parseState = FPData;
break;
}
}
data[i] = *p;
i++;
filterRuleEndPos++;
p++;
}
if (parseState == FPStart) {
f->filterType = FTEmpty;
return;
}
if (preserveRules) {
int ruleTextLength = filterRuleEndPos - filterRuleStart;
f->ruleDefinition = new char[ruleTextLength + 1];
memcpy(f->ruleDefinition, filterRuleStart, ruleTextLength);
f->ruleDefinition[ruleTextLength] = '\0';
}
data[i] = '\0';
f->data = new char[i + 1];
memcpy(f->data, data, i + 1);
char fingerprintBuffer[AdBlockClient::kFingerprintSize + 1];
fingerprintBuffer[AdBlockClient::kFingerprintSize] = '\0';
if (f->filterType == FTElementHiding) {
if (simpleCosmeticFilters && !f->domainList) {
simpleCosmeticFilters->Add(CosmeticFilter(data));
}
} else if (f->filterType == FTElementHidingException) {
if (simpleCosmeticFilters && f->domainList) {
simpleCosmeticFilters->Remove(CosmeticFilter(data));
}
} else if (exceptionBloomFilter
&& (f->filterType & FTException) && (f->filterType & FTHostOnly)) {
// cout << "add host anchored exception bloom filter: " << f->host << endl;
hostAnchoredExceptionHashSet->Add(*f);
} else if (hostAnchoredHashSet && (f->filterType & FTHostOnly)) {
// cout << "add host anchored bloom filter: " << f->host << endl;
hostAnchoredHashSet->Add(*f);
} else if (AdBlockClient::getFingerprint(fingerprintBuffer, *f)) {
if (exceptionBloomFilter && f->filterType & FTException) {
exceptionBloomFilter->add(fingerprintBuffer);
} else if (bloomFilter) {
// cout << "add fingerprint: " << fingerprintBuffer
// << ", from string: " << f->data << endl;
bloomFilter->add(fingerprintBuffer);
}
}
}
AdBlockClient::AdBlockClient() : filters(nullptr),
cosmeticFilters(nullptr),
htmlFilters(nullptr),
exceptionFilters(nullptr),
noFingerprintFilters(nullptr),
noFingerprintExceptionFilters(nullptr),
noFingerprintDomainOnlyFilters(nullptr),
noFingerprintAntiDomainOnlyFilters(nullptr),
noFingerprintDomainOnlyExceptionFilters(nullptr),
noFingerprintAntiDomainOnlyExceptionFilters(nullptr),
numFilters(0),
numCosmeticFilters(0),
numHtmlFilters(0),
numExceptionFilters(0),
numNoFingerprintFilters(0),
numNoFingerprintExceptionFilters(0),
numNoFingerprintDomainOnlyFilters(0),
numNoFingerprintAntiDomainOnlyFilters(0),
numNoFingerprintDomainOnlyExceptionFilters(0),
numNoFingerprintAntiDomainOnlyExceptionFilters(0),
numHostAnchoredFilters(0),
numHostAnchoredExceptionFilters(0),
bloomFilter(nullptr),
exceptionBloomFilter(nullptr),
hostAnchoredHashSet(nullptr),
hostAnchoredExceptionHashSet(nullptr),
noFingerprintDomainHashSet(nullptr),
noFingerprintAntiDomainHashSet(nullptr),
noFingerprintDomainExceptionHashSet(nullptr),
noFingerprintAntiDomainExceptionHashSet(nullptr),
badFingerprintsHashSet(nullptr),
numFalsePositives(0),
numExceptionFalsePositives(0),
numBloomFilterSaves(0),
numExceptionBloomFilterSaves(0),
numHashSetSaves(0),
numExceptionHashSetSaves(0),
deserializedBuffer(nullptr) {
}
AdBlockClient::~AdBlockClient() {
clear();
}
// Clears all data and stats from the AdBlockClient
void AdBlockClient::clear() {
if (filters) {
delete[] filters;
filters = nullptr;
}
if (cosmeticFilters) {
delete[] cosmeticFilters;
cosmeticFilters = nullptr;
}
if (htmlFilters) {
delete[] htmlFilters;
htmlFilters = nullptr;
}
if (exceptionFilters) {
delete[] exceptionFilters;
exceptionFilters = nullptr;
}
if (noFingerprintFilters) {
delete[] noFingerprintFilters;
noFingerprintFilters = nullptr;
}
if (noFingerprintExceptionFilters) {
delete[] noFingerprintExceptionFilters;
noFingerprintExceptionFilters = nullptr;
}
if (noFingerprintDomainOnlyFilters) {
delete[] noFingerprintDomainOnlyFilters;
noFingerprintDomainOnlyFilters = nullptr;
}
if (noFingerprintAntiDomainOnlyFilters) {
delete[] noFingerprintAntiDomainOnlyFilters;
noFingerprintAntiDomainOnlyFilters = nullptr;
}
if (noFingerprintDomainOnlyExceptionFilters) {
delete[] noFingerprintDomainOnlyExceptionFilters;
noFingerprintDomainOnlyExceptionFilters = nullptr;
}
if (noFingerprintAntiDomainOnlyExceptionFilters) {
delete[] noFingerprintAntiDomainOnlyExceptionFilters;
noFingerprintAntiDomainOnlyExceptionFilters = nullptr;
}
if (bloomFilter) {
delete bloomFilter;
bloomFilter = nullptr;
}
if (exceptionBloomFilter) {
delete exceptionBloomFilter;
exceptionBloomFilter = nullptr;
}
if (hostAnchoredHashSet) {
delete hostAnchoredHashSet;
hostAnchoredHashSet = nullptr;
}
if (hostAnchoredExceptionHashSet) {
delete hostAnchoredExceptionHashSet;
hostAnchoredExceptionHashSet = nullptr;
}
if (noFingerprintDomainHashSet) {
delete noFingerprintDomainHashSet;
noFingerprintDomainHashSet = nullptr;
}
if (noFingerprintAntiDomainHashSet) {
delete noFingerprintAntiDomainHashSet;
noFingerprintAntiDomainHashSet = nullptr;
}
if (noFingerprintDomainExceptionHashSet) {
delete noFingerprintDomainExceptionHashSet;
noFingerprintDomainExceptionHashSet = nullptr;
}
if (noFingerprintAntiDomainExceptionHashSet) {
delete noFingerprintAntiDomainExceptionHashSet;
noFingerprintAntiDomainExceptionHashSet = nullptr;
}
if (badFingerprintsHashSet) {
delete badFingerprintsHashSet;
badFingerprintsHashSet = nullptr;
}
numFilters = 0;
numCosmeticFilters = 0;
numHtmlFilters = 0;
numExceptionFilters = 0;
numNoFingerprintFilters = 0;
numNoFingerprintExceptionFilters = 0;
numNoFingerprintDomainOnlyFilters = 0;
numNoFingerprintAntiDomainOnlyFilters = 0;
numNoFingerprintDomainOnlyExceptionFilters = 0;
numNoFingerprintAntiDomainOnlyExceptionFilters = 0;
numHostAnchoredFilters = 0;
numHostAnchoredExceptionFilters = 0;
numFalsePositives = 0;
numExceptionFalsePositives = 0;
numBloomFilterSaves = 0;
numExceptionBloomFilterSaves = 0;
numHashSetSaves = 0;
numExceptionHashSetSaves = 0;
}
bool AdBlockClient::hasMatchingFilters(Filter *filter, int numFilters,
const char *input,
int inputLen,
FilterOption contextOption,
const char *contextDomain,
BloomFilter *inputBloomFilter,
const char *inputHost,
int inputHostLen,
Filter **matchingFilter) {
for (int i = 0; i < numFilters; i++) {
if (filter->matches(input, inputLen, contextOption,
contextDomain, inputBloomFilter, inputHost, inputHostLen)) {
if (filter->tagLen == 0 ||
tagExists(std::string(filter->tag, filter->tagLen))) {
if (matchingFilter) {
*matchingFilter = filter;
}
return true;
}
}
filter++;
}
if (matchingFilter) {
*matchingFilter = nullptr;
}
return false;
}
void discoverMatchingPrefix(BadFingerprintsHashSet *badFingerprintsHashSet,
const char *str,
BloomFilter *bloomFilter,
int prefixLen = AdBlockClient::kFingerprintSize) {
char sz[32];
memset(sz, 0, sizeof(sz));
int strLen = static_cast<int>(strlen(str));
for (int i = 0; i < strLen - prefixLen + 1; i++) {
if (bloomFilter->exists(str + i, prefixLen)) {
memcpy(sz, str + i, prefixLen);
// cout << "Bad fingerprint: " << sz << endl;
if (badFingerprintsHashSet) {
badFingerprintsHashSet->Add(BadFingerprint(sz));
}
// We only want the first bad fingerprint since that's the one
// that led us here.
// If you do all bad fingerprint detection here it will lead to too many
// bad fingerprints, which then leads to too many no fingerprint rules.
// And too many no fingerprint rules causes perf problems.
return;
}
// memcpy(sz, str + i, prefixLen);
// cout << "Good fingerprint: " << sz;
}
}
bool isNoFingerprintDomainHashSetMiss(HashSet<NoFingerprintDomain> *hashSet,
const char *host, int hostLen) {
if (!hashSet) {
return false;
}
const char *start = host + hostLen;
// Skip past the TLD
while (start != host) {
start--;
if (*(start) == '.') {
break;
}
}
while (start != host) {
if (*(start - 1) == '.') {
if (hashSet->Find(NoFingerprintDomain(start,
static_cast<int>(host + hostLen - start)))) {
return false;
}
}
start--;
}
return !hashSet->Find(NoFingerprintDomain(start,
static_cast<int>(host + hostLen - start)));
}
bool AdBlockClient::isHostAnchoredHashSetMiss(const char *input, int inputLen,
HashSet<Filter> *hashSet,
const char *inputHost,
int inputHostLen,
FilterOption contextOption,
const char *contextDomain,
Filter **foundFilter) {
if (!hashSet) {
return false;
}
const char *start = inputHost + inputHostLen;
// Skip past the TLD
while (start != inputHost) {
start--;
if (*(start) == '.') {
break;
}
}
while (start != inputHost) {
if (*(start - 1) == '.') {
Filter *filter = hashSet->Find(Filter(start,
static_cast<int>(inputHost + inputHostLen - start),
nullptr, start, inputHostLen - (start - inputHost)));
if (filter && filter->matches(input, inputLen,
contextOption, contextDomain)) {
if (filter->tagLen == 0 ||
tagExists(std::string(filter->tag, filter->tagLen))) {
if (foundFilter) {
*foundFilter = filter;
}
return false;
}
}
}
start--;
}
Filter *filter = hashSet->Find(Filter(start,
static_cast<int>(inputHost + inputHostLen - start), nullptr,
start, inputHostLen));
if (!filter) {
return true;
}
bool result = !filter->matches(input, inputLen, contextOption, contextDomain);
if (!result) {
if (filter->tagLen > 0 &&
!tagExists(std::string(filter->tag, filter->tagLen))) {
return true;
}
if (foundFilter) {
*foundFilter = filter;
}
}
return result;
}
bool AdBlockClient::matches(const char* input, FilterOption contextOption,
const char* contextDomain, Filter** matchedFilter,
Filter** matchedExceptionFilter) {
if (matchedFilter) {
*matchedFilter = nullptr;
}
if (matchedExceptionFilter) {
*matchedExceptionFilter = nullptr;
}
int inputLen = static_cast<int>(strlen(input));
if (!isBlockableProtocol(input, inputLen)) {
return false;
}
int inputHostLen;
const char *inputHost = getUrlHost(input, &inputHostLen);
int contextDomainLen = 0;
if (contextDomain) {
contextDomainLen = static_cast<int>(strlen(contextDomain));
}
// If neither first party nor third party was specified, try to figure it out
if (contextDomain && !(contextOption & (FOThirdParty | FONotThirdParty))) {
if (isThirdPartyHost(contextDomain, contextDomainLen,
inputHost, static_cast<int>(inputHostLen))) {
contextOption =
static_cast<FilterOption>(contextOption | FOThirdParty);
} else {
contextOption =
static_cast<FilterOption>(contextOption | FONotThirdParty);
}
}
// Optimization for the manual filter checks which are needed.
// Avoid having to check individual filters if the filter parts are not found
// inside the input bloom filter.
HashFn2Byte hashFns[] = { hashFn2Byte };
BloomFilter inputBloomFilter(10, 1024, hashFns, 1);
for (int i = 1; i < inputLen; i++) {
inputBloomFilter.add(input + i - 1, 2);
}
// We always have to check noFingerprintFilters because the bloom filter opt
// cannot be used for them
bool hasMatch = false;
// Only bother checking the no fingerprint domain related filters if needed
if (!isNoFingerprintDomainHashSetMiss(
noFingerprintDomainHashSet, contextDomain, contextDomainLen)) {
hasMatch = hasMatch || hasMatchingFilters(noFingerprintDomainOnlyFilters,
numNoFingerprintDomainOnlyFilters, input, inputLen, contextOption,
contextDomain, &inputBloomFilter, inputHost, inputHostLen,
matchedFilter);
}
if (isNoFingerprintDomainHashSetMiss(
noFingerprintAntiDomainHashSet, contextDomain, contextDomainLen)) {
hasMatch = hasMatch ||
hasMatchingFilters(noFingerprintAntiDomainOnlyFilters,
numNoFingerprintAntiDomainOnlyFilters, input, inputLen, contextOption,
contextDomain, &inputBloomFilter, inputHost, inputHostLen,
matchedFilter);
}
hasMatch = hasMatch || hasMatchingFilters(noFingerprintFilters,
numNoFingerprintFilters, input, inputLen, contextOption,
contextDomain, &inputBloomFilter, inputHost, inputHostLen,
matchedFilter);
// If no noFingerprintFilters were hit, check the bloom filter substring
// fingerprint for the normal
// filter list. If no substring exists for the input then we know for sure
// the URL should not be blocked.
bool bloomFilterMiss = false;
bool hostAnchoredHashSetMiss = false;
if (!hasMatch) {
bloomFilterMiss = bloomFilter
&& !bloomFilter->substringExists(input, AdBlockClient::kFingerprintSize);
hostAnchoredHashSetMiss = isHostAnchoredHashSetMiss(input, inputLen,
hostAnchoredHashSet, inputHost, inputHostLen,
contextOption, contextDomain, matchedFilter);
if (bloomFilterMiss && hostAnchoredHashSetMiss) {
if (bloomFilterMiss) {
numBloomFilterSaves++;
}
if (hostAnchoredHashSetMiss) {
numHashSetSaves++;
}
return false;
}
hasMatch = !hostAnchoredHashSetMiss;
}
// We need to check the filters list manually because there is either a match
// or a false positive
if (!hasMatch && !bloomFilterMiss) {
hasMatch = hasMatchingFilters(filters, numFilters, input, inputLen,
contextOption, contextDomain, &inputBloomFilter,
inputHost, inputHostLen, matchedFilter);
// If there's still no match after checking the block filters, then no need
// to try to block this because there is a false positive.
if (!hasMatch) {
numFalsePositives++;
if (badFingerprintsHashSet) {
// cout << "false positive for input: " << input << " bloomFilterMiss: "
// << bloomFilterMiss << ", hostAnchoredHashSetMiss: "
// << hostAnchoredHashSetMiss << endl;
discoverMatchingPrefix(badFingerprintsHashSet, input, bloomFilter);
}
return false;
}
}
bool hasExceptionMatch = false;
// Only bother checking the no fingerprint domain related filters if needed
if (!isNoFingerprintDomainHashSetMiss(
noFingerprintDomainExceptionHashSet, contextDomain, contextDomainLen)) {
hasExceptionMatch = hasExceptionMatch ||
hasMatchingFilters(noFingerprintDomainOnlyExceptionFilters,
numNoFingerprintDomainOnlyExceptionFilters, input, inputLen,
contextOption, contextDomain, &inputBloomFilter, inputHost,
inputHostLen, matchedExceptionFilter);
}
if (isNoFingerprintDomainHashSetMiss(
noFingerprintAntiDomainExceptionHashSet, contextDomain,
contextDomainLen)) {
hasExceptionMatch = hasExceptionMatch ||
hasMatchingFilters(noFingerprintAntiDomainOnlyExceptionFilters,
numNoFingerprintAntiDomainOnlyExceptionFilters, input, inputLen,
contextOption, contextDomain, &inputBloomFilter, inputHost, inputHostLen,
matchedExceptionFilter);
}
hasExceptionMatch = hasExceptionMatch ||
hasMatchingFilters(noFingerprintExceptionFilters,
numNoFingerprintExceptionFilters, input, inputLen, contextOption,
contextDomain, &inputBloomFilter, inputHost, inputHostLen,
matchedExceptionFilter);
// If there's a matching no fingerprint exception then we can just return
// right away because we shouldn't block
if (hasExceptionMatch) {
return false;
}
bool bloomExceptionFilterMiss = exceptionBloomFilter
&& !exceptionBloomFilter->substringExists(input,
AdBlockClient::kFingerprintSize);
bool hostAnchoredExceptionHashSetMiss =
isHostAnchoredHashSetMiss(input, inputLen, hostAnchoredExceptionHashSet,
inputHost, inputHostLen, contextOption, contextDomain,
matchedExceptionFilter);
// Now that we have a matching rule, we should check if no exception rule
// hits, if none hits, we should block
if (bloomExceptionFilterMiss && hostAnchoredExceptionHashSetMiss) {
if (bloomExceptionFilterMiss) {
numExceptionBloomFilterSaves++;
}
if (hostAnchoredExceptionHashSetMiss) {
numExceptionHashSetSaves++;
}
return true;
}
// If tehre wasn't an exception has set miss, it was a hit, and hash set is
// deterministic so we shouldn't block this resource.
if (!hostAnchoredExceptionHashSetMiss) {
numExceptionHashSetSaves++;
return false;
}
if (!bloomExceptionFilterMiss) {
if (!hasMatchingFilters(exceptionFilters, numExceptionFilters, input,
inputLen, contextOption, contextDomain,
&inputBloomFilter, inputHost, inputHostLen,
matchedExceptionFilter)) {
// False positive on the exception filter list
numExceptionFalsePositives++;
// cout << "exception false positive for input: " << input << endl;
if (badFingerprintsHashSet) {
discoverMatchingPrefix(badFingerprintsHashSet,
input, exceptionBloomFilter);
}
return true;
}
}
return false;
}
/**
* Obtains the first matching filter or nullptr, and if one is found, finds
* the first matching exception filter or nullptr.
*
* @return true if the filter should be blocked
*/
bool AdBlockClient::findMatchingFilters(const char *input,
FilterOption contextOption,
const char *contextDomain,
Filter **matchingFilter,
Filter **matchingExceptionFilter) {
*matchingFilter = nullptr;
*matchingExceptionFilter = nullptr;
int inputLen = static_cast<int>(strlen(input));
int inputHostLen;
const char *inputHost = getUrlHost(input, &inputHostLen);
int contextDomainLen = 0;
if (contextDomain) {
contextDomainLen = static_cast<int>(strlen(contextDomain));
}
// If neither first party nor third party was specified, try to figure it out
if (contextDomain && !(contextOption & (FOThirdParty | FONotThirdParty))) {
if (isThirdPartyHost(contextDomain, contextDomainLen,
inputHost, static_cast<int>(inputHostLen))) {
contextOption =
static_cast<FilterOption>(contextOption | FOThirdParty);
} else {
contextOption =
static_cast<FilterOption>(contextOption | FONotThirdParty);
}
}
hasMatchingFilters(noFingerprintFilters,
numNoFingerprintFilters, input, inputLen, contextOption,
contextDomain, nullptr,
inputHost, inputHostLen, matchingFilter);
if (!*matchingFilter) {
hasMatchingFilters(noFingerprintDomainOnlyFilters,
numNoFingerprintDomainOnlyFilters, input, inputLen, contextOption,
contextDomain, nullptr,
inputHost, inputHostLen, matchingFilter);
}
if (!*matchingFilter) {
hasMatchingFilters(noFingerprintAntiDomainOnlyFilters,
numNoFingerprintAntiDomainOnlyFilters, input, inputLen, contextOption,
contextDomain, nullptr,
inputHost, inputHostLen, matchingFilter);
}
if (!*matchingFilter) {
hasMatchingFilters(filters,