forked from StevenBlack/hosts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
updateHostsFile.py
1765 lines (1404 loc) · 50.7 KB
/
updateHostsFile.py
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
#!/usr/bin/env python3
# Script by Ben Limmer
# https://github.com/l1m5
#
# This Python script will combine all the host files you provide
# as sources into one, unique host file to keep your internet browsing happy.
import argparse
import fnmatch
import json
import locale
import os
import platform
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from glob import glob
import lxml # noqa: F401
from bs4 import BeautifulSoup
# Detecting Python 3 for version-dependent implementations
PY3 = sys.version_info >= (3, 0)
if PY3:
from urllib.request import urlopen
else:
raise Exception("We do not support Python 2 anymore.")
# Syntactic sugar for "sudo" command in UNIX / Linux
if platform.system() == "OpenBSD":
SUDO = ["/usr/bin/doas"]
else:
SUDO = ["/usr/bin/env", "sudo"]
# Project Settings
BASEDIR_PATH = os.path.dirname(os.path.realpath(__file__))
def get_defaults():
"""
Helper method for getting the default settings.
Returns
-------
default_settings : dict
A dictionary of the default settings when updating host information.
"""
return {
"numberofrules": 0,
"datapath": path_join_robust(BASEDIR_PATH, "data"),
"freshen": True,
"replace": False,
"backup": False,
"skipstatichosts": False,
"keepdomaincomments": True,
"extensionspath": path_join_robust(BASEDIR_PATH, "extensions"),
"extensions": [],
"compress": False,
"minimise": False,
"outputsubfolder": "",
"hostfilename": "hosts",
"targetip": "0.0.0.0",
"sourcedatafilename": "update.json",
"sourcesdata": [],
"readmefilename": "readme.md",
"readmetemplate": path_join_robust(BASEDIR_PATH, "readme_template.md"),
"readmedata": {},
"readmedatafilename": path_join_robust(BASEDIR_PATH, "readmeData.json"),
"exclusionpattern": r"([a-zA-Z\d-]+\.){0,}",
"exclusionregexs": [],
"exclusions": [],
"commonexclusions": ["hulu.com"],
"blacklistfile": path_join_robust(BASEDIR_PATH, "blacklist"),
"whitelistfile": path_join_robust(BASEDIR_PATH, "whitelist"),
}
# End Project Settings
def main():
parser = argparse.ArgumentParser(
description="Creates a unified hosts "
"file from hosts stored in the data subfolders."
)
parser.add_argument(
"--auto",
"-a",
dest="auto",
default=False,
action="store_true",
help="Run without prompting.",
)
parser.add_argument(
"--backup",
"-b",
dest="backup",
default=False,
action="store_true",
help="Backup the hosts files before they are overridden.",
)
parser.add_argument(
"--extensions",
"-e",
dest="extensions",
default=[],
nargs="*",
help="Host extensions to include in the final hosts file.",
)
parser.add_argument(
"--ip",
"-i",
dest="targetip",
default="0.0.0.0",
help="Target IP address. Default is 0.0.0.0.",
)
parser.add_argument(
"--keepdomaincomments",
"-k",
dest="keepdomaincomments",
action="store_false",
default=True,
help="Do not keep domain line comments.",
)
parser.add_argument(
"--noupdate",
"-n",
dest="noupdate",
default=False,
action="store_true",
help="Don't update from host data sources.",
)
parser.add_argument(
"--skipstatichosts",
"-s",
dest="skipstatichosts",
default=False,
action="store_true",
help="Skip static localhost entries in the final hosts file.",
)
parser.add_argument(
"--nogendata",
"-g",
dest="nogendata",
default=False,
action="store_true",
help="Skip generation of readmeData.json",
)
parser.add_argument(
"--output",
"-o",
dest="outputsubfolder",
default="",
help="Output subfolder for generated hosts file.",
)
parser.add_argument(
"--replace",
"-r",
dest="replace",
default=False,
action="store_true",
help="Replace your active hosts file with this new hosts file.",
)
parser.add_argument(
"--flush-dns-cache",
"-f",
dest="flushdnscache",
default=False,
action="store_true",
help="Attempt to flush DNS cache after replacing the hosts file.",
)
parser.add_argument(
"--compress",
"-c",
dest="compress",
default=False,
action="store_true",
help="Compress the hosts file ignoring non-necessary lines "
"(empty lines and comments) and putting multiple domains in "
"each line. Improve the performance under Windows.",
)
parser.add_argument(
"--minimise",
"-m",
dest="minimise",
default=False,
action="store_true",
help="Minimise the hosts file ignoring non-necessary lines "
"(empty lines and comments).",
)
parser.add_argument(
"--whitelist",
"-w",
dest="whitelistfile",
default=path_join_robust(BASEDIR_PATH, "whitelist"),
help="Whitelist file to use while generating hosts files.",
)
parser.add_argument(
"--blacklist",
"-x",
dest="blacklistfile",
default=path_join_robust(BASEDIR_PATH, "blacklist"),
help="Blacklist file to use while generating hosts files.",
)
global settings
options = vars(parser.parse_args())
options["outputpath"] = path_join_robust(BASEDIR_PATH, options["outputsubfolder"])
options["freshen"] = not options["noupdate"]
settings = get_defaults()
settings.update(options)
data_path = settings["datapath"]
extensions_path = settings["extensionspath"]
settings["sources"] = list_dir_no_hidden(data_path)
settings["extensionsources"] = list_dir_no_hidden(extensions_path)
# All our extensions folders...
settings["extensions"] = [
os.path.basename(item) for item in list_dir_no_hidden(extensions_path)
]
# ... intersected with the extensions passed-in as arguments, then sorted.
settings["extensions"] = sorted(
list(set(options["extensions"]).intersection(settings["extensions"]))
)
auto = settings["auto"]
exclusion_regexes = settings["exclusionregexs"]
source_data_filename = settings["sourcedatafilename"]
update_sources = prompt_for_update(freshen=settings["freshen"], update_auto=auto)
if update_sources:
update_all_sources(source_data_filename, settings["hostfilename"])
gather_exclusions = prompt_for_exclusions(skip_prompt=auto)
if gather_exclusions:
common_exclusions = settings["commonexclusions"]
exclusion_pattern = settings["exclusionpattern"]
exclusion_regexes = display_exclusion_options(
common_exclusions=common_exclusions,
exclusion_pattern=exclusion_pattern,
exclusion_regexes=exclusion_regexes,
)
extensions = settings["extensions"]
sources_data = update_sources_data(
settings["sourcesdata"],
datapath=data_path,
extensions=extensions,
extensionspath=extensions_path,
sourcedatafilename=source_data_filename,
)
merge_file = create_initial_file()
remove_old_hosts_file(
path_join_robust(settings["outputpath"], "hosts"), settings["backup"]
)
if settings["compress"]:
final_file = open(path_join_robust(settings["outputpath"], "hosts"), "w+b")
compressed_file = tempfile.NamedTemporaryFile()
remove_dups_and_excl(merge_file, exclusion_regexes, compressed_file)
compress_file(compressed_file, settings["targetip"], final_file)
elif settings["minimise"]:
final_file = open(path_join_robust(settings["outputpath"], "hosts"), "w+b")
minimised_file = tempfile.NamedTemporaryFile()
remove_dups_and_excl(merge_file, exclusion_regexes, minimised_file)
minimise_file(minimised_file, settings["targetip"], final_file)
else:
final_file = remove_dups_and_excl(merge_file, exclusion_regexes)
number_of_rules = settings["numberofrules"]
output_subfolder = settings["outputsubfolder"]
skip_static_hosts = settings["skipstatichosts"]
write_opening_header(
final_file,
extensions=extensions,
numberofrules=number_of_rules,
outputsubfolder=output_subfolder,
skipstatichosts=skip_static_hosts,
)
final_file.close()
if not settings["nogendata"]:
update_readme_data(
settings["readmedatafilename"],
extensions=extensions,
numberofrules=number_of_rules,
outputsubfolder=output_subfolder,
sourcesdata=sources_data,
)
print_success(
"Success! The hosts file has been saved in folder "
+ output_subfolder
+ "\nIt contains "
+ "{:,}".format(number_of_rules)
+ " unique entries."
)
move_file = prompt_for_move(
final_file,
auto=auto,
replace=settings["replace"],
skipstatichosts=skip_static_hosts,
)
# We only flush the DNS cache if we have
# moved a new hosts file into place.
if move_file:
prompt_for_flush_dns_cache(
flush_cache=settings["flushdnscache"], prompt_flush=not auto
)
# Prompt the User
def prompt_for_update(freshen, update_auto):
"""
Prompt the user to update all hosts files.
If requested, the function will update all data sources after it
checks that a hosts file does indeed exist.
Parameters
----------
freshen : bool
Whether data sources should be updated. This function will return
if it is requested that data sources not be updated.
update_auto : bool
Whether or not to automatically update all data sources.
Returns
-------
update_sources : bool
Whether or not we should update data sources for exclusion files.
"""
# Create a hosts file if it doesn't exist.
hosts_file = path_join_robust(BASEDIR_PATH, "hosts")
if not os.path.isfile(hosts_file):
try:
open(hosts_file, "w+").close()
except (IOError, OSError):
# Starting in Python 3.3, IOError is aliased
# OSError. However, we have to catch both for
# Python 2.x failures.
print_failure(
"ERROR: No 'hosts' file in the folder. Try creating one manually."
)
if not freshen:
return
prompt = "Do you want to update all data sources?"
if update_auto or query_yes_no(prompt):
return True
elif not update_auto:
print("OK, we'll stick with what we've got locally.")
return False
def prompt_for_exclusions(skip_prompt):
"""
Prompt the user to exclude any custom domains from being blocked.
Parameters
----------
skip_prompt : bool
Whether or not to skip prompting for custom domains to be excluded.
If true, the function returns immediately.
Returns
-------
gather_exclusions : bool
Whether or not we should proceed to prompt the user to exclude any
custom domains beyond those in the whitelist.
"""
prompt = (
"Do you want to exclude any domains?\n"
"For example, hulu.com video streaming must be able to access "
"its tracking and ad servers in order to play video."
)
if not skip_prompt:
if query_yes_no(prompt):
return True
else:
print("OK, we'll only exclude domains in the whitelist.")
return False
def prompt_for_flush_dns_cache(flush_cache, prompt_flush):
"""
Prompt the user to flush the DNS cache.
Parameters
----------
flush_cache : bool
Whether to flush the DNS cache without prompting.
prompt_flush : bool
If `flush_cache` is False, whether we should prompt for flushing the
cache. Otherwise, the function returns immediately.
"""
if flush_cache:
flush_dns_cache()
elif prompt_flush:
if query_yes_no("Attempt to flush the DNS cache?"):
flush_dns_cache()
def prompt_for_move(final_file, **move_params):
"""
Prompt the user to move the newly created hosts file to its designated
location in the OS.
Parameters
----------
final_file : file
The file object that contains the newly created hosts data.
move_params : kwargs
Dictionary providing additional parameters for moving the hosts file
into place. Currently, those fields are:
1) auto
2) replace
3) skipstatichosts
Returns
-------
move_file : bool
Whether or not the final hosts file was moved.
"""
skip_static_hosts = move_params["skipstatichosts"]
if move_params["replace"] and not skip_static_hosts:
move_file = True
elif move_params["auto"] or skip_static_hosts:
move_file = False
else:
prompt = "Do you want to replace your existing hosts file with the newly generated file?"
move_file = query_yes_no(prompt)
if move_file:
move_hosts_file_into_place(final_file)
return move_file
# End Prompt the User
def sort_sources(sources):
"""
Sorts the sources.
The idea is that all Steven Black's list, file or entries
get on top and the rest sorted alphabetically.
Parameters
----------
sources: list
The sources to sort.
"""
result = sorted(
sources.copy(),
key=lambda x: x.lower().replace("-", "").replace("_", "").replace(" ", ""),
)
# Steven Black's repositories/files/lists should be on top!
steven_black_positions = [
x for x, y in enumerate(result) if "stevenblack" in y.lower()
]
for index in steven_black_positions:
result.insert(0, result.pop(index))
return result
# Exclusion logic
def display_exclusion_options(common_exclusions, exclusion_pattern, exclusion_regexes):
"""
Display the exclusion options to the user.
This function checks whether a user wants to exclude particular domains,
and if so, excludes them.
Parameters
----------
common_exclusions : list
A list of common domains that are excluded from being blocked. One
example is Hulu. This setting is set directly in the script and cannot
be overwritten by the user.
exclusion_pattern : str
The exclusion pattern with which to create the domain regex.
exclusion_regexes : list
The list of regex patterns used to exclude domains.
Returns
-------
aug_exclusion_regexes : list
The original list of regex patterns potentially with additional
patterns from domains that the user chooses to exclude.
"""
for exclusion_option in common_exclusions:
prompt = "Do you want to exclude the domain " + exclusion_option + " ?"
if query_yes_no(prompt):
exclusion_regexes = exclude_domain(
exclusion_option, exclusion_pattern, exclusion_regexes
)
else:
continue
if query_yes_no("Do you want to exclude any other domains?"):
exclusion_regexes = gather_custom_exclusions(
exclusion_pattern, exclusion_regexes
)
return exclusion_regexes
def gather_custom_exclusions(exclusion_pattern, exclusion_regexes):
"""
Gather custom exclusions from the user.
Parameters
----------
exclusion_pattern : str
The exclusion pattern with which to create the domain regex.
exclusion_regexes : list
The list of regex patterns used to exclude domains.
Returns
-------
aug_exclusion_regexes : list
The original list of regex patterns potentially with additional
patterns from domains that the user chooses to exclude.
"""
# We continue running this while-loop until the user
# says that they have no more domains to exclude.
while True:
domain_prompt = "Enter the domain you want to exclude (e.g. facebook.com): "
user_domain = input(domain_prompt)
if is_valid_domain_format(user_domain):
exclusion_regexes = exclude_domain(
user_domain, exclusion_pattern, exclusion_regexes
)
continue_prompt = "Do you have more domains you want to enter?"
if not query_yes_no(continue_prompt):
break
return exclusion_regexes
def exclude_domain(domain, exclusion_pattern, exclusion_regexes):
"""
Exclude a domain from being blocked.
This creates the domain regex by which to exclude this domain and appends
it a list of already-existing exclusion regexes.
Parameters
----------
domain : str
The filename or regex pattern to exclude.
exclusion_pattern : str
The exclusion pattern with which to create the domain regex.
exclusion_regexes : list
The list of regex patterns used to exclude domains.
Returns
-------
aug_exclusion_regexes : list
The original list of regex patterns with one additional pattern from
the `domain` input.
"""
exclusion_regex = re.compile(exclusion_pattern + domain)
exclusion_regexes.append(exclusion_regex)
return exclusion_regexes
def matches_exclusions(stripped_rule, exclusion_regexes):
"""
Check whether a rule matches an exclusion rule we already provided.
If this function returns True, that means this rule should be excluded
from the final hosts file.
Parameters
----------
stripped_rule : str
The rule that we are checking.
exclusion_regexes : list
The list of regex patterns used to exclude domains.
Returns
-------
matches_exclusion : bool
Whether or not the rule string matches a provided exclusion.
"""
stripped_domain = stripped_rule.split()[1]
for exclusionRegex in exclusion_regexes:
if exclusionRegex.search(stripped_domain):
return True
return False
# End Exclusion Logic
# Update Logic
def update_sources_data(sources_data, **sources_params):
"""
Update the sources data and information for each source.
Parameters
----------
sources_data : list
The list of sources data that we are to update.
sources_params : kwargs
Dictionary providing additional parameters for updating the
sources data. Currently, those fields are:
1) datapath
2) extensions
3) extensionspath
4) sourcedatafilename
Returns
-------
update_sources_data : list
The original source data list with new source data appended.
"""
source_data_filename = sources_params["sourcedatafilename"]
for source in sort_sources(
recursive_glob(sources_params["datapath"], source_data_filename)
):
update_file = open(source, "r", encoding="UTF-8")
update_data = json.load(update_file)
sources_data.append(update_data)
update_file.close()
for source in sources_params["extensions"]:
source_dir = path_join_robust(sources_params["extensionspath"], source)
for update_file_path in sort_sources(
recursive_glob(source_dir, source_data_filename)
):
update_file = open(update_file_path, "r")
update_data = json.load(update_file)
sources_data.append(update_data)
update_file.close()
return sources_data
def jsonarray(json_array_string):
"""
Transformer, converts a json array string hosts into one host per
line, prefixing each line with "127.0.0.1 ".
Parameters
----------
json_array_string : str
The json array string in the form
'["example1.com", "example1.com", ...]'
"""
temp_list = json.loads(json_array_string)
hostlines = "127.0.0.1 " + "\n127.0.0.1 ".join(temp_list)
return hostlines
def update_all_sources(source_data_filename, host_filename):
"""
Update all host files, regardless of folder depth.
Parameters
----------
source_data_filename : str
The name of the filename where information regarding updating
sources for a particular URL is stored. This filename is assumed
to be the same for all sources.
host_filename : str
The name of the file in which the updated source information
is stored for a particular URL. This filename is assumed to be
the same for all sources.
"""
# The transforms we support
transform_methods = {"jsonarray": jsonarray}
all_sources = sort_sources(recursive_glob("*", source_data_filename))
for source in all_sources:
update_file = open(source, "r", encoding="UTF-8")
update_data = json.load(update_file)
update_file.close()
update_url = update_data["url"]
update_transforms = []
if update_data.get("transforms"):
update_transforms = update_data["transforms"]
print("Updating source " + os.path.dirname(source) + " from " + update_url)
try:
updated_file = get_file_by_url(update_url)
# spin the transforms as required
for transform in update_transforms:
updated_file = transform_methods[transform](updated_file)
# get rid of carriage-return symbols
updated_file = updated_file.replace("\r", "")
hosts_file = open(
path_join_robust(BASEDIR_PATH, os.path.dirname(source), host_filename),
"wb",
)
write_data(hosts_file, updated_file)
hosts_file.close()
except Exception:
print("Error in updating source: ", update_url)
# End Update Logic
# File Logic
def create_initial_file():
"""
Initialize the file in which we merge all host files for later pruning.
"""
merge_file = tempfile.NamedTemporaryFile()
# spin the sources for the base file
for source in sort_sources(
recursive_glob(settings["datapath"], settings["hostfilename"])
):
start = "# Start {}\n\n".format(os.path.basename(os.path.dirname(source)))
end = "# End {}\n\n".format(os.path.basename(os.path.dirname(source)))
with open(source, "r", encoding="UTF-8") as curFile:
write_data(merge_file, start + curFile.read() + end)
# spin the sources for extensions to the base file
for source in settings["extensions"]:
for filename in sort_sources(
recursive_glob(
path_join_robust(settings["extensionspath"], source),
settings["hostfilename"],
)
):
with open(filename, "r") as curFile:
write_data(merge_file, curFile.read())
maybe_copy_example_file(settings["blacklistfile"])
if os.path.isfile(settings["blacklistfile"]):
with open(settings["blacklistfile"], "r") as curFile:
write_data(merge_file, curFile.read())
return merge_file
def compress_file(input_file, target_ip, output_file):
"""
Reduce the file dimension removing non-necessary lines (empty lines and
comments) and putting multiple domains in each line.
Reducing the number of lines of the file, the parsing under Microsoft
Windows is much faster.
Parameters
----------
input_file : file
The file object that contains the hostnames that we are reducing.
target_ip : str
The target IP address.
output_file : file
The file object that will contain the reduced hostnames.
"""
input_file.seek(0) # reset file pointer
write_data(output_file, "\n")
target_ip_len = len(target_ip)
lines = [target_ip]
lines_index = 0
for line in input_file.readlines():
line = line.decode("UTF-8")
if line.startswith(target_ip):
if lines[lines_index].count(" ") < 9:
lines[lines_index] += (
" " + line[target_ip_len : line.find("#")].strip() # noqa: E203
)
else:
lines[lines_index] += "\n"
lines.append(line[: line.find("#")].strip())
lines_index += 1
for line in lines:
write_data(output_file, line)
input_file.close()
def minimise_file(input_file, target_ip, output_file):
"""
Reduce the file dimension removing non-necessary lines (empty lines and
comments).
Parameters
----------
input_file : file
The file object that contains the hostnames that we are reducing.
target_ip : str
The target IP address.
output_file : file
The file object that will contain the reduced hostnames.
"""
input_file.seek(0) # reset file pointer
write_data(output_file, "\n")
lines = []
for line in input_file.readlines():
line = line.decode("UTF-8")
if line.startswith(target_ip):
lines.append(line[: line.find("#")].strip() + "\n")
for line in lines:
write_data(output_file, line)
input_file.close()
def remove_dups_and_excl(merge_file, exclusion_regexes, output_file=None):
"""
Remove duplicates and remove hosts that we are excluding.
We check for duplicate hostnames as well as remove any hostnames that
have been explicitly excluded by the user.
Parameters
----------
merge_file : file
The file object that contains the hostnames that we are pruning.
exclusion_regexes : list
The list of regex patterns used to exclude domains.
output_file : file
The file object in which the result is written. If None, the file
'settings["outputpath"]' will be created.
"""
number_of_rules = settings["numberofrules"]
maybe_copy_example_file(settings["whitelistfile"])
if os.path.isfile(settings["whitelistfile"]):
with open(settings["whitelistfile"], "r") as ins:
for line in ins:
line = line.strip(" \t\n\r")
if line and not line.startswith("#"):
settings["exclusions"].append(line)
if not os.path.exists(settings["outputpath"]):
os.makedirs(settings["outputpath"])
if output_file is None:
final_file = open(path_join_robust(settings["outputpath"], "hosts"), "w+b")
else:
final_file = output_file
merge_file.seek(0) # reset file pointer
hostnames = {"localhost", "localhost.localdomain", "local", "broadcasthost"}
exclusions = settings["exclusions"]
for line in merge_file.readlines():
write_line = True
# Explicit encoding
line = line.decode("UTF-8")
# replace tabs with space
line = line.replace("\t+", " ")
# see gh-271: trim trailing whitespace, periods
line = line.rstrip(" .")
# Testing the first character doesn't require startswith
if line[0] == "#" or re.match(r"^\s*$", line[0]):
write_data(final_file, line)
continue
if "::1" in line:
continue
stripped_rule = strip_rule(line) # strip comments
if not stripped_rule or matches_exclusions(stripped_rule, exclusion_regexes):
continue
# Normalize rule
hostname, normalized_rule = normalize_rule(
stripped_rule,
target_ip=settings["targetip"],
keep_domain_comments=settings["keepdomaincomments"],
)
for exclude in exclusions:
if re.search(r"[\s\.]" + re.escape(exclude) + r"\s", line):
write_line = False
break
if normalized_rule and (hostname not in hostnames) and write_line:
write_data(final_file, normalized_rule)
hostnames.add(hostname)
number_of_rules += 1
settings["numberofrules"] = number_of_rules
merge_file.close()
if output_file is None:
return final_file
def normalize_rule(rule, target_ip, keep_domain_comments):
"""
Standardize and format the rule string provided.
Parameters
----------
rule : str
The rule whose spelling and spacing we are standardizing.
target_ip : str
The target IP address for the rule.
keep_domain_comments : bool
Whether or not to keep comments regarding these domains in
the normalized rule.
Returns
-------
normalized_rule : tuple
A tuple of the hostname and the rule string with spelling
and spacing reformatted.
"""
"""
first try: IP followed by domain
"""
regex = r"^\s*(\d{1,3}\.){3}\d{1,3}\s+([\w\.-]+[a-zA-Z])(.*)"
result = re.search(regex, rule)
if result:
hostname, suffix = result.group(2, 3)
# Explicitly lowercase and trim the hostname.
hostname = hostname.lower().strip()
rule = "%s %s" % (target_ip, hostname)
if suffix and keep_domain_comments:
if not suffix.strip().startswith("#"):
rule += " #%s" % suffix
else:
rule += " %s" % suffix
return hostname, rule + "\n"