Debian Codegraph @

utils/generate-domains-blocklist/generate-domains-blocklist.py

raw symbols SCIP
1 #! /usr/bin/env python3
2
3 # run with python generate-domains-blocklist.py > list.txt.tmp && mv -f list.txt.tmp list
4
5 from __future__ import print_function
6
7 import argparse
8 import re
9 import sys
10 import fnmatch
11 import concurrent.futures
12 import time
13
14 try:
15 import urllib2 as urllib
16
17 URLLIB_NEW = False
18 except (ImportError, ModuleNotFoundError):
19 import urllib.request as urllib
20 from urllib.request import Request
21
22 URLLIB_NEW = True
23
24
25 def setup_logging(output_file=None):
26 log_info = sys.stdout if output_file else sys.stderr
27 log_err = sys.stderr
28 return log_info, log_err
29
30
31 def parse_trusted_list(content):
32 rx_comment = re.compile(r"^(#|$)")
33 rx_inline_comment = re.compile(r"\s*#\s*[a-z0-9-].*$")
34 rx_trusted = re.compile(r"^([*a-z0-9.-]+)\s*(@\S+)?$")
35 rx_timed = re.compile(r".+\s*@\S+$")
36
37 names = set()
38 time_restrictions = {}
39 globs = set()
40 rx_set = [rx_trusted]
41 for line in content.splitlines():
42 line = str.lower(str.strip(line))
43 if rx_comment.match(line):
44 continue
45 line = str.strip(rx_inline_comment.sub("", line))
46 if is_glob(line) and not rx_timed.match(line):
47 globs.add(line)
48 names.add(line)
49 continue
50 for rx in rx_set:
51 matches = rx.match(line)
52 if not matches:
53 continue
54 name = matches.group(1)
55 names.add(name)
56 time_restriction = matches.group(2)
57 if time_restriction:
58 time_restrictions[name] = time_restriction
59 return names, time_restrictions, globs
60
61
62 def parse_list(content, trusted=False):
63 if trusted:
64 return parse_trusted_list(content)
65
66 rx_comment = re.compile(r"^(#|$)")
67 rx_inline_comment = re.compile(r"\s*#\s*[a-z0-9-].*$")
68 rx_u = re.compile(
69 r"^@*\|\|([a-z0-9][a-z0-9.-]*[.][a-z]{2,})\^?(\$(popup|third-party))?$"
70 )
71 rx_l = re.compile(r"^([a-z0-9][a-z0-9.-]*[.][a-z]{2,})$")
72 rx_lw = re.compile(r"^[*][.]([a-z0-9][a-z0-9.-]*[.][a-z]{2,})$")
73 rx_h = re.compile(
74 r"^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}\s+([a-z0-9][a-z0-9.-]*[.][a-z]{2,})$"
75 )
76 rx_mdl = re.compile(r'^"[^"]+","([a-z0-9][a-z0-9.-]*[.][a-z]{2,})",')
77 rx_b = re.compile(r"^([a-z0-9][a-z0-9.-]*[.][a-z]{2,}),.+,[0-9: /-]+,")
78 rx_dq = re.compile(r"^address=/([a-z0-9][a-z0-9.-]*[.][a-z]{2,})/.")
79
80 names = set()
81 time_restrictions = {}
82 globs = set()
83 rx_set = [rx_u, rx_l, rx_lw, rx_h, rx_mdl, rx_b, rx_dq]
84 for line in content.splitlines():
85 line = str.lower(str.strip(line))
86 if rx_comment.match(line):
87 continue
88 line = str.strip(rx_inline_comment.sub("", line))
89 for rx in rx_set:
90 matches = rx.match(line)
91 if not matches:
92 continue
93 name = matches.group(1)
94 names.add(name)
95 return names, time_restrictions, globs
96
97
98 def print_restricted_name(output_fd, name, time_restrictions):
99 if name in time_restrictions:
100 print("{}\t{}".format(name, time_restrictions[name]), file=output_fd, end="\n")
101 else:
102 print(
103 "# ignored: [{}] was in the time-restricted list, "
104 "but without a time restriction label".format(name),
105 file=output_fd,
106 end="\n",
107 )
108
109
110 def load_from_url(url, timeout):
111 req = urllib.Request(url=url, headers={"User-Agent": "dnscrypt-proxy"})
112 trusted = False
113
114 if URLLIB_NEW:
115 req_type = req.type
116 else:
117 req_type = req.get_type()
118 if req_type == "file":
119 trusted = True
120
121 response = None
122 try:
123 response = urllib.urlopen(req, timeout=int(timeout))
124 content = response.read() # "The read operation timed out"
125 except Exception as err:
126 raise Exception("[{}] could not be loaded: {}".format(url, err))
127 if trusted is False and response.getcode() != 200:
128 raise Exception("[{}] returned HTTP code {}".format(url, response.getcode()))
129 if URLLIB_NEW:
130 content = content.decode("utf-8", errors="replace")
131
132 return content, trusted
133
134
135 def name_cmp(name):
136 parts = name.split(".")
137 parts.reverse()
138 return str.join(".", parts)
139
140
141 def is_glob(pattern):
142 maybe_glob = False
143 for i in range(len(pattern)):
144 c = pattern[i]
145 if c == "?" or c == "[":
146 maybe_glob = True
147 elif c == "*" and i != 0:
148 if i < len(pattern) - 1 or pattern[i - 1] == ".":
149 maybe_glob = True
150 if maybe_glob:
151 try:
152 fnmatch.fnmatch("example", pattern)
153 return True
154 except:
155 pass
156 return False
157
158
159 def covered_by_glob(globs, name):
160 if name in globs:
161 return False
162 for glob in globs:
163 try:
164 if fnmatch.fnmatch(name, glob):
165 return True
166 except:
167 pass
168 return False
169
170
171 def has_suffix(names, name):
172 parts = str.split(name, ".")
173 while parts:
174 parts = parts[1:]
175 if str.join(".", parts) in names:
176 return True
177 return False
178
179
180 def allowlist_from_url(url, timeout):
181 if not url:
182 return set()
183 content, trusted = load_from_url(url, timeout)
184
185 names, _time_restrictions, _globs = parse_list(content, trusted)
186 return names
187
188 STOP_RETRY = False
189
190 def load_url_with_retry(url, timeout, tries=3, retry_delay=2):
191 log_info, log_err = setup_logging()
192 for attempt in range(tries):
193 try_msg = f"try: {attempt + 1}/{tries}"
194 try:
195 log_info.write(f"[{try_msg}] Loading data from [{url}]\n")
196 content, trusted = load_from_url(url, timeout)
197 log_err.write(f"[{try_msg}] [{url}] OK\n")
198 return content, trusted
199 except Exception as e:
200 log_err.write(f"[{try_msg}] {e}\n")
201 if STOP_RETRY:
202 break
203 if attempt < tries - 1:
204 time.sleep(retry_delay)
205 else:
206 raise e
207
208
209 def load_blocklists_parallel(urls, timeout, ignore_retrieval_failure):
210 log_info, log_err = setup_logging()
211 blocklists = {}
212 all_names = set()
213 all_globs = set()
214
215 with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
216 future_to_url = {
217 executor.submit(load_url_with_retry, url, timeout): url
218 for url in urls
219 }
220
221 # Useful for bad network situations
222 return_when = concurrent.futures.FIRST_EXCEPTION
223 if ignore_retrieval_failure:
224 return_when = concurrent.futures.ALL_COMPLETED
225 finished, unfinished = concurrent.futures.wait(future_to_url, None, return_when)
226 # Return early
227 if len(unfinished) > 0:
228 # Cancel unstarted tasks
229 for f in unfinished:
230 if not f.done():
231 f.cancel()
232 # Stop retries
233 global STOP_RETRY
234 STOP_RETRY = True
235 # Threads won't be terminated forcibly
236 if not ignore_retrieval_failure:
237 sys.exit(1)
238
239 for future in finished:
240 url = future_to_url[future]
241 try:
242 content, trusted = future.result()
243 names, _time_restrictions, globs = parse_list(content, trusted)
244 blocklists[url] = names
245 all_names |= names
246 all_globs |= globs
247 except Exception as e:
248 log_err.write(f"{e}\n")
249 if not ignore_retrieval_failure:
250 sys.exit(1)
251
252 return blocklists, all_names, all_globs
253
254
255 def blocklists_from_config_file(
256 file, allowlist, time_restricted_url, ignore_retrieval_failure, output_file, timeout
257 ):
258 log_info, log_err = setup_logging(output_file)
259
260 # Get URLs from config file
261 urls = []
262 with open(file) as fd:
263 for line in fd:
264 line = str.strip(line)
265 if str.startswith(line, "#") or line == "":
266 continue
267 urls.append(line)
268
269 # Load blocklists in parallel
270 blocklists, all_names, all_globs = load_blocklists_parallel(
271 urls, timeout, ignore_retrieval_failure
272 )
273
274 # Load allowed names
275 allowed_names = set()
276
277 # Time-based blocklist
278 if time_restricted_url and not re.match(r"^[a-z0-9]+:", time_restricted_url):
279 time_restricted_url = "file:" + time_restricted_url
280
281 output_fd = sys.stdout
282 if output_file:
283 output_fd = open(output_file, "w")
284
285 if time_restricted_url:
286 try:
287 time_restricted_content, _trusted = load_from_url(
288 time_restricted_url, timeout
289 )
290 time_restricted_names, time_restrictions, _globs = parse_trusted_list(
291 time_restricted_content
292 )
293
294 if time_restricted_names:
295 print(
296 "########## Time-based blocklist ##########\n",
297 file=output_fd,
298 end="\n",
299 )
300 for name in time_restricted_names:
301 print_restricted_name(output_fd, name, time_restrictions)
302
303 # Time restricted names should be allowed, or they could be always blocked
304 allowed_names |= time_restricted_names
305 except Exception as e:
306 log_err.write(f"Error loading time-restricted list: {str(e)}\n")
307
308 # Allowed list
309 if allowlist and not re.match(r"^[a-z0-9]+:", allowlist):
310 allowlist = "file:" + allowlist
311
312 try:
313 allowed_names |= allowlist_from_url(allowlist, timeout)
314 except Exception as e:
315 log_err.write(f"Error loading allowlist: {str(e)}\n")
316
317 # Process blocklists
318 unique_names = set()
319 for url, names in blocklists.items():
320 print(
321 "\n\n########## Blocklist from {} ##########\n".format(url),
322 file=output_fd,
323 end="\n",
324 )
325 ignored, glob_ignored, allowed = 0, 0, 0
326 list_names = []
327 for name in names:
328 if covered_by_glob(all_globs, name):
329 glob_ignored = glob_ignored + 1
330 elif has_suffix(all_names, name) or name in unique_names:
331 ignored = ignored + 1
332 elif has_suffix(allowed_names, name) or name in allowed_names:
333 allowed = allowed + 1
334 else:
335 list_names.append(name)
336 unique_names.add(name)
337
338 list_names.sort(key=name_cmp)
339 if ignored:
340 print("# Ignored duplicates: {}".format(ignored), file=output_fd, end="\n")
341 if glob_ignored:
342 print(
343 "# Ignored due to overlapping local patterns: {}".format(glob_ignored),
344 file=output_fd,
345 end="\n",
346 )
347 if allowed:
348 print(
349 "# Ignored entries due to the allowlist: {}".format(allowed),
350 file=output_fd,
351 end="\n",
352 )
353 if ignored or glob_ignored or allowed:
354 print(file=output_fd, end="\n")
355 for name in list_names:
356 print(name, file=output_fd, end="\n")
357
358 output_fd.close()
359
360
361 def main():
362 argp = argparse.ArgumentParser(
363 description="Create a unified blocklist from a set of local and remote files"
364 )
365 argp.add_argument(
366 "-c",
367 "--config",
368 default="domains-blocklist.conf",
369 help="file containing blocklist sources",
370 )
371 argp.add_argument(
372 "-w",
373 "--whitelist",
374 help=argparse.SUPPRESS,
375 )
376 argp.add_argument(
377 "-a",
378 "--allowlist",
379 default="domains-allowlist.txt",
380 help="file containing a set of names to exclude from the blocklist",
381 )
382 argp.add_argument(
383 "-r",
384 "--time-restricted",
385 default="domains-time-restricted.txt",
386 help="file containing a set of names to be time restricted",
387 )
388 argp.add_argument(
389 "-i",
390 "--ignore-retrieval-failure",
391 action="store_true",
392 help="generate list even if some urls couldn't be retrieved",
393 )
394 argp.add_argument(
395 "-o",
396 "--output-file",
397 default=None,
398 help="save generated blocklist to a text file with the provided file name",
399 )
400 argp.add_argument("-t", "--timeout", default=30, help="URL open timeout in seconds")
401 argp.add_argument(
402 "-p",
403 "--progress",
404 action="store_true",
405 help="show download progress information",
406 )
407
408 args = argp.parse_args()
409
410 whitelist = args.whitelist
411 if whitelist:
412 print(
413 "The option to provide a set of names to exclude from the blocklist has been changed from -w to -a\n"
414 )
415 argp.print_help()
416 exit(1)
417
418 start_time = time.time()
419
420 log_info, _ = setup_logging(args.output_file)
421 if args.progress:
422 log_info.write("Starting blocklist generation...\n")
423
424 blocklists_from_config_file(
425 args.config,
426 args.allowlist,
427 args.time_restricted,
428 args.ignore_retrieval_failure,
429 args.output_file,
430 args.timeout,
431 )
432
433 if args.progress:
434 duration = time.time() - start_time
435 log_info.write(f"Blocklist generation completed in {duration:.2f} seconds\n")
436
437
438 if __name__ == "__main__":
439 main()