-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.php
executable file
·89 lines (71 loc) · 2.24 KB
/
convert.php
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
<?php
// fetch data
$rawdata = explode("\n", trim(file_get_contents('hosts.txt')));
echo count($rawdata), " Entries processed..\n";
// fetch whitelist
$whitelist = explode("\n", trim(file_get_contents('whitelist.txt')));
echo count($whitelist), " Whitelist Hosts processed..\n";
// utility function
// @TODO performance optimization...
function isWhitelisted($host){
global $whitelist;
foreach ($whitelist as $entry){
// wildcard ?
if (strpos($entry, '.') == 0){
// strip dot
$entry = substr($entry, 1);
if (substr($host, -strlen($entry)) === $entry){
return true;
}
// singlular match
}else{
// match found ?
if ($entry == $host){
return true;
}
}
}
// not in the list
return false;
}
// domains to hostname => [subdomain] array
$hosts = array();
// process data
foreach ($rawdata as $row){
// valid line ? format <IP> <hostname>
if (preg_match('/^0\.0\.0\.0\s+(\w+\S+\.)(\w+\.[a-z]{2,10})\s*$/Ui', $row, $matches) === 1){
$fullDomain = $matches[1] . $matches[2];
// host entry in whitelist ?
if (!isWhitelisted($fullDomain)){
// domain in list ?
if (!isset($hosts[$matches[2]])){
$hosts[$matches[2]] = array();
}
// push host
$hosts[$matches[2]][] = $matches[1];
}
}
}
echo count(array_keys($hosts)), " Domains total..\n";
// reduce array to dnsmasq format
$dnsmasq = '';
array_walk($hosts, function($hostnames, $domain) use (&$dnsmasq){
// generate local zone entry
foreach ($hostnames as $host){
$dnsmasq .= 'address=/' . $host . $domain . '/0.0.0.0'."\n";
}
});
// reduce array to unbound format
$unbound = '';
array_walk($hosts, function($hostnames, $domain) use (&$unbound){
// generate local zone entry
$z = 'local-zone: "' . $domain . '." typetransparent'."\n";
foreach ($hostnames as $host){
$z .= 'local-data: "' . $host . $domain . '. A 0.0.0.0"'."\n";
}
// append result
$unbound .= $z;
});
// save
file_put_contents('dist/dnsmasq.adblock.conf', $dnsmasq);
file_put_contents('dist/unbound.adblock.conf', $unbound);