-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhblock
More file actions
executable file
·691 lines (619 loc) · 27.3 KB
/
hblock
File metadata and controls
executable file
·691 lines (619 loc) · 27.3 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
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
#!/bin/sh
# Version: 3.1.3
# Author: Héctor Molinero Fernández <hector@molinero.dev>
# License: MIT, https://opensource.org/licenses/MIT
# Repository: https://github.com/hectorm/hblock
set -eu
export LC_ALL='C'
# Emulate ksh if the shell is zsh.
if [ -n "${ZSH_VERSION-}" ]; then emulate -L ksh; fi
# Define system and user configuration directories.
if [ -z "${ETCDIR+x}" ]; then ETCDIR='/etc'; fi
if [ -z "${XDG_CONFIG_HOME+x}" ]; then XDG_CONFIG_HOME="${HOME-}/.config"; fi
# Built-in header.
HOSTNAME="${HOSTNAME-"$(uname -n)"}"
HBLOCK_HEADER_BUILTIN="$(cat <<-EOF
127.0.0.1 localhost ${HOSTNAME?}
255.255.255.255 broadcasthost
::1 localhost ${HOSTNAME?}
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOF
)"
# Built-in footer.
HBLOCK_FOOTER_BUILTIN=''
# Built-in sources.
HBLOCK_SOURCES_BUILTIN="$(cat <<-'EOF'
https://raw.githubusercontent.com/hectorm/hmirror/master/data/adaway.org/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/adblock-nocoin-list/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/adguard-simplified/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/antipopads/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/digitalside-threat-intel/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/easylist/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/easyprivacy/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/eth-phishing-detect/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/fademind-add.2o7net/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/fademind-add.dead/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/fademind-add.risk/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/fademind-add.spam/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/gfrogeye-firstparty-trackers/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/hostsvn/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/kadhosts/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/lightswitch05-ads-and-tracking/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/matomo.org-spammers/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/mitchellkrogza-badd-boyz-hosts/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/pgl.yoyo.org/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/phishing.army/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/socram8888-notonmyshift/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/someonewhocares.org/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/spam404.com/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/stevenblack/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/ublock/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/ublock-abuse/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/ublock-badware/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/ublock-privacy/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/urlhaus/list.txt
https://raw.githubusercontent.com/hectorm/hmirror/master/data/winhelp2002.mvps.org/list.txt
EOF
)"
# Built-in allowlist.
HBLOCK_ALLOWLIST_BUILTIN=''
# Built-in denylist.
HBLOCK_DENYLIST_BUILTIN="$(cat <<-'EOF'
# Special domain that is used to check if hBlock is enabled.
hblock-check.molinero.dev
EOF
)"
# Parse command line options.
optParse() {
while [ "${#}" -gt '0' ]; do
case "${1?}" in
# Short options that accept an argument need a "*" in their pattern because they can be
# found in the "-A<value>" form.
'-O'*|'--output') optArgStr "${@-}"; outputFile="${optArg?}"; shift "${optShift:?}" ;;
'-H'*|'--header') optArgStr "${@-}"; headerFile="${optArg?}"; shift "${optShift:?}" ;;
'-F'*|'--footer') optArgStr "${@-}"; footerFile="${optArg?}"; shift "${optShift:?}" ;;
'-S'*|'--sources') optArgStr "${@-}"; sourcesFile="${optArg?}"; shift "${optShift:?}" ;;
'-A'*|'--allowlist') optArgStr "${@-}"; allowlistFile="${optArg?}"; shift "${optShift:?}" ;;
'-D'*|'--denylist') optArgStr "${@-}"; denylistFile="${optArg?}"; shift "${optShift:?}" ;;
'-R'*|'--redirection') optArgStr "${@-}"; redirection="${optArg?}"; shift "${optShift:?}" ;;
'-W'*|'--wrap') optArgStr "${@-}"; wrap="${optArg?}"; shift "${optShift:?}" ;;
'-T'*|'--template') optArgStr "${@-}"; template="${optArg?}"; shift "${optShift:?}" ;;
'-C'*|'--comment') optArgStr "${@-}"; comment="${optArg?}"; shift "${optShift:?}" ;;
'-l' |'--lenient'|'--no-lenient') optArgBool "${@-}"; lenient="${optArg:?}" ;;
'-r' |'--regex'|'--no-regex') optArgBool "${@-}"; regex="${optArg:?}" ;;
'-c' |'--continue'|'--no-continue') optArgBool "${@-}"; continue="${optArg:?}" ;;
'-q' |'--quiet'|'--no-quiet') optArgBool "${@-}"; quiet="${optArg:?}" ;;
'-x'*|'--color') optArgStr "${@-}"; color="${optArg?}"; shift "${optShift:?}" ;;
'-v' |'--version') showVersion ;;
'-h' |'--help') showHelp ;;
# If "--" is found, the remaining positional arguments are saved and the parsing ends.
--) shift; posArgs="${posArgs-} ${*-}"; break ;;
# If a long option in the form "--opt=value" is found, it is split into "--opt" and "value".
--*=*) optSplitEquals "${@-}"; shift; set -- "${optName:?}" "${optArg?}" "${@-}"; continue ;;
# If an option did not match any pattern, an error is thrown.
-?|--*) optDie "Illegal option ${1:?}" ;;
# If multiple short options in the form "-AB" are found, they are split into "-A" and "-B".
-?*) optSplitShort "${@-}"; shift; set -- "${optAName:?}" "${optBName:?}" "${@-}"; continue ;;
# If a positional argument is found, it is saved.
*) posArgs="${posArgs-} ${1?}" ;;
esac
shift
done
}
optSplitShort() {
optAName="${1%"${1#??}"}"; optBName="-${1#??}"
}
optSplitEquals() {
optName="${1%="${1#--*=}"}"; optArg="${1#--*=}"
}
optArgStr() {
if [ -n "${1#??}" ] && [ "${1#--}" = "${1:?}" ]; then optArg="${1#??}"; optShift='0';
elif [ -n "${2+x}" ]; then optArg="${2-}"; optShift='1';
else optDie "No argument for ${1:?} option"; fi
}
optArgBool() {
if [ "${1#--no-}" = "${1:?}" ]; then optArg='true';
else optArg='false'; fi
}
optDie() {
printf -- '%s\n' "${@-}" "Try 'hblock --help' for more information" >&2
exit 2
}
# Show help and quit.
showHelp() {
printf -- '%s\n' "$(sed -e 's/%NL/\n/g' <<-EOF
Usage: hblock [OPTION]...
hBlock is a POSIX-compliant shell script that gets a list of domains that serve
ads, tracking scripts and malware from multiple sources and creates a hosts
file, among other formats, that prevents your system from connecting to them.
Options:
-O, --output <FILE|->, \${HBLOCK_OUTPUT_FILE}%NL
Output file location.%NL
If equals "-", it is printed to stdout.%NL
(default: ${outputFile?})%NL
-H, --header <FILE|builtin|none|->, \${HBLOCK_HEADER_FILE}%NL
File to be included at the beginning of the output file.%NL
If equals "builtin", the built-in value is used.%NL
If equals "none", an empty value is used.%NL
If equals "-", the stdin content is used.%NL
If unspecified and any of the following files exists, its content is used.%NL
\${XDG_CONFIG_HOME}/hblock/header%NL
${ETCDIR?}/hblock/header%NL
(default: ${headerFile?})%NL
-F, --footer <FILE|builtin|none|->, \${HBLOCK_FOOTER_FILE}%NL
File to be included at the end of the output file.%NL
If equals "builtin", the built-in value is used.%NL
If equals "none", an empty value is used.%NL
If equals "-", the stdin content is used.%NL
If unspecified and any of the following files exists, its content is used.%NL
\${XDG_CONFIG_HOME}/hblock/footer%NL
${ETCDIR?}/hblock/footer%NL
(default: ${footerFile?})%NL
-S, --sources <FILE|builtin|none|->, \${HBLOCK_SOURCES_FILE}%NL
File with line separated URLs used to generate the blocklist.%NL
If equals "builtin", the built-in value is used.%NL
If equals "none", an empty value is used.%NL
If equals "-", the stdin content is used.%NL
If unspecified and any of the following files exists, its content is used.%NL
\${XDG_CONFIG_HOME}/hblock/sources.list%NL
${ETCDIR?}/hblock/sources.list%NL
(default: ${sourcesFile?})%NL
-A, --allowlist <FILE|builtin|none|->, \${HBLOCK_ALLOWLIST_FILE}%NL
File with line separated entries to be removed from the blocklist.%NL
If equals "builtin", the built-in value is used.%NL
If equals "none", an empty value is used.%NL
If equals "-", the stdin content is used.%NL
If unspecified and any of the following files exists, its content is used.%NL
\${XDG_CONFIG_HOME}/hblock/allow.list%NL
${ETCDIR?}/hblock/allow.list%NL
(default: ${allowlistFile?})%NL
-D, --denylist <FILE|builtin|none|->, \${HBLOCK_DENYLIST_FILE}%NL
File with line separated entries to be added to the blocklist.%NL
If equals "builtin", the built-in value is used.%NL
If equals "none", an empty value is used.%NL
If equals "-", the stdin content is used.%NL
If unspecified and any of the following files exists, its content is used.%NL
\${XDG_CONFIG_HOME}/hblock/deny.list%NL
${ETCDIR?}/hblock/deny.list%NL
(default: ${denylistFile?})%NL
-R, --redirection <REDIRECTION>, \${HBLOCK_REDIRECTION}%NL
Redirection for all entries in the blocklist.%NL
(default: ${redirection?})%NL
-W, --wrap <NUMBER>, \${HBLOCK_WRAP}%NL
Break blocklist lines after this number of entries.%NL
(default: ${wrap?})%NL
-T, --template <TEMPLATE>, \${HBLOCK_TEMPLATE}%NL
Template applied to each entry.%NL
%D = <DOMAIN>, %R = <REDIRECTION>%NL
(default: ${template?})%NL
-C, --comment <COMMENT>, \${HBLOCK_COMMENT}%NL
Character used for comments.%NL
(default: ${comment?})%NL
-l, --[no-]lenient, \${HBLOCK_LENIENT}%NL
Match all entries from sources regardless of their IP, instead of
0.0.0.0, 127.0.0.1, ::, ::1 or nothing.%NL
(default: ${lenient?})%NL
-r, --[no-]regex, \${HBLOCK_REGEX}%NL
Use POSIX BREs in the allowlist instead of fixed strings.%NL
(default: ${regex?})%NL
-c, --[no-]continue, \${HBLOCK_CONTINUE}%NL
Do not abort if a download error occurs.%NL
(default: ${continue?})%NL
-q, --[no-]quiet, \${HBLOCK_QUIET}%NL
Suppress non-error messages.%NL
(default: ${quiet?})%NL
-x, --color <auto|true|false>, \${HBLOCK_COLOR}%NL
Colorize the output.%NL
(default: ${color?})%NL
-v, --version%NL
Show version number and quit.%NL
-h, --help%NL
Show this help and quit.
Report bugs to: <https://github.com/hectorm/hblock/issues>
EOF
)"
exit 0
}
# Show version number and quit.
showVersion() {
getMetadata() { sed -ne 's|^# '"${1:?}"':[[:blank:]]*\(.\{1,\}\)$|\1|p' -- "${0:?}"; }
printf -- '%s\n' "$(cat <<-EOF
hBlock $(getMetadata 'Version')
Author: $(getMetadata 'Author')
License: $(getMetadata 'License')
Repository: $(getMetadata 'Repository')
EOF
)"
exit 0
}
# Check if a program exists.
exists() {
# shellcheck disable=SC2230
if command -v true; then command -v -- "${1:?}"
elif eval type type; then eval type -- "${1:?}"
else which -- "${1:?}"; fi >/dev/null 2>&1
}
# Pretty print methods.
printInfo() {
if [ "${quiet-}" != 'true' ]; then
if [ "${color-}" != 'true' ]; then printf -- '[INFO] %s\n' "${@-}"
else printf -- '\033[0m[\033[1;32mINFO\033[0m] %s\n' "${@-}"; fi
fi
}
printWarn() {
if [ "${color-}" != 'true' ]; then printf -- '[WARN] %s\n' "${@-}" >&2
else printf -- '\033[0m[\033[1;33mWARN\033[0m] %s\n' "${@-}" >&2; fi
}
printError() {
if [ "${color-}" != 'true' ]; then printf -- '[ERROR] %s\n' "${@-}" >&2
else printf -- '\033[0m[\033[1;31mERROR\033[0m] %s\n' "${@-}" >&2; fi
}
printList() {
if [ "${quiet-}" != 'true' ]; then
if [ "${color-}" != 'true' ]; then printf -- ' * %s\n' "${@-}"
else printf -- '\033[0m \033[1;36m*\033[0m %s\n' "${@-}"; fi
fi
}
# Create a temporary directory.
createTempDir() {
if exists mktemp; then mktemp -d
else
# Since POSIX does not specify mktemp utility, use this as fallback.
# And wait a second as a horrible hack to avoid name collisions.
rnd="$(sleep 1; awk 'BEGIN{srand();printf("%08x",rand()*(2**31-1))}')"
dir="${TMPDIR:-/tmp}/tmp.${$}${rnd:?}"
(umask 077 && mkdir -- "${dir:?}")
printf -- '%s' "${dir:?}"
fi
}
# Print to stdout the contents of a URL.
fetchUrl() {
# If the protocol is "file://" we can omit the download and simply use cat.
if [ "${1#file://}" != "${1:?}" ]; then cat -- "${1#file://}"
else
userAgent='Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'
if exists curl; then curl -fsSL -A "${userAgent:?}" -- "${1:?}"
elif exists wget; then wget -qO- -U "${userAgent:?}" -- "${1:?}"
elif exists fetch; then fetch -qo- --user-agent="${userAgent:?}" -- "${1:?}"
else
printError 'curl, wget or fetch are required for this script'
exit 1
fi
fi
}
main() {
usrConfDir="${XDG_CONFIG_HOME?}/hblock"
sysConfDir="${ETCDIR?}/hblock"
# Source environment file if exists.
# shellcheck disable=SC1090
if [ -f "${usrConfDir:?}/environment" ]; then
set -a; . "${usrConfDir:?}/environment"; set +a
elif [ -f "${sysConfDir:?}/environment" ]; then
set -a; . "${sysConfDir:?}/environment"; set +a
fi
# Output file location.
outputFile="${HBLOCK_OUTPUT_FILE-"${ETCDIR?}/hosts"}"
# File to be included at the beginning of the output file.
headerFile='builtin'
if [ -n "${HBLOCK_HEADER+x}" ]; then
HBLOCK_HEADER_BUILTIN="${HBLOCK_HEADER?}"
elif [ -n "${HBLOCK_HEADER_FILE+x}" ]; then
headerFile="${HBLOCK_HEADER_FILE?}"
elif [ -f "${usrConfDir:?}/header" ]; then
headerFile="${usrConfDir:?}/header"
elif [ -f "${sysConfDir:?}/header" ]; then
headerFile="${sysConfDir:?}/header"
fi
# File to be included at the end of the output file.
footerFile='builtin'
if [ -n "${HBLOCK_FOOTER+x}" ]; then
HBLOCK_FOOTER_BUILTIN="${HBLOCK_FOOTER?}"
elif [ -n "${HBLOCK_FOOTER_FILE+x}" ]; then
footerFile="${HBLOCK_FOOTER_FILE?}"
elif [ -f "${usrConfDir:?}/footer" ]; then
footerFile="${usrConfDir:?}/footer"
elif [ -f "${sysConfDir:?}/footer" ]; then
footerFile="${sysConfDir:?}/footer"
fi
# File with line separated URLs used to generate the blocklist.
sourcesFile='builtin'
if [ -n "${HBLOCK_SOURCES+x}" ]; then
HBLOCK_SOURCES_BUILTIN="${HBLOCK_SOURCES?}"
elif [ -n "${HBLOCK_SOURCES_FILE+x}" ]; then
sourcesFile="${HBLOCK_SOURCES_FILE?}"
elif [ -f "${usrConfDir:?}/sources.list" ]; then
sourcesFile="${usrConfDir:?}/sources.list"
elif [ -f "${sysConfDir:?}/sources.list" ]; then
sourcesFile="${sysConfDir:?}/sources.list"
fi
# File with line separated entries to be removed from the blocklist.
allowlistFile='builtin'
if [ -n "${HBLOCK_ALLOWLIST+x}" ]; then
HBLOCK_ALLOWLIST_BUILTIN="${HBLOCK_ALLOWLIST?}"
elif [ -n "${HBLOCK_ALLOWLIST_FILE+x}" ]; then
allowlistFile="${HBLOCK_ALLOWLIST_FILE?}"
elif [ -f "${usrConfDir:?}/allow.list" ]; then
allowlistFile="${usrConfDir:?}/allow.list"
elif [ -f "${sysConfDir:?}/allow.list" ]; then
allowlistFile="${sysConfDir:?}/allow.list"
fi
# File with line separated entries to be added to the blocklist.
denylistFile='builtin'
if [ -n "${HBLOCK_DENYLIST+x}" ]; then
HBLOCK_DENYLIST_BUILTIN="${HBLOCK_DENYLIST?}"
elif [ -n "${HBLOCK_DENYLIST_FILE+x}" ]; then
denylistFile="${HBLOCK_DENYLIST_FILE?}"
elif [ -f "${usrConfDir:?}/deny.list" ]; then
denylistFile="${usrConfDir:?}/deny.list"
elif [ -f "${sysConfDir:?}/deny.list" ]; then
denylistFile="${sysConfDir:?}/deny.list"
fi
# Redirection for all entries in the blocklist.
redirection="${HBLOCK_REDIRECTION-"0.0.0.0"}"
# Break blocklist lines after this number of entries.
wrap="${HBLOCK_WRAP-"1"}"
# Template applied to each entry.
template="${HBLOCK_TEMPLATE-"%R %D"}"
# Character used for comments.
comment="${HBLOCK_COMMENT-"#"}"
# Match all entries from sources, regardless of their IP.
lenient="${HBLOCK_LENIENT-"false"}"
# Use POSIX BREs instead of fixed strings.
regex="${HBLOCK_REGEX-"false"}"
# Abort if a download error occurs.
continue="${HBLOCK_CONTINUE-"false"}"
# Colorize the output.
color="${HBLOCK_COLOR-"auto"}"
# Suppress non-error messages.
quiet="${HBLOCK_QUIET-"false"}"
# Parse command line options.
# shellcheck disable=SC2086
{ optParse "${@-}"; set -- ${posArgs-}; }
if [ "${color:?}" = 'auto' ]; then
# Check color support, but honor ${NO_COLOR} variable (https://no-color.org).
if [ -t 1 ] && [ -z "${NO_COLOR+x}" ]; then
color='true'
else
color='false'
fi
fi
# Create a temporary work directory.
tmpWorkDir="$(createTempDir)"
# shellcheck disable=SC2154
trap 'ret="$?"; rm -rf -- "${tmpWorkDir:?}"; trap - EXIT; exit "${ret:?}"' EXIT TERM INT HUP
# Check the header file.
case "${headerFile:?}" in
# If the file value equals "-", use stdin.
'-') headerFile="${tmpWorkDir:?}/header"; cat <&0 > "${headerFile:?}" ;;
# If the file value equals "none", use an empty file.
'none') headerFile="${tmpWorkDir:?}/header"; true > "${headerFile:?}" ;;
# If the file value equals "builtin", use the built-in value.
'builtin') headerFile="${tmpWorkDir:?}/header"; printf -- '%s' "${HBLOCK_HEADER_BUILTIN?}" > "${headerFile:?}" ;;
# If the file does not exist, throw an error.
*) [ -e "${headerFile:?}" ] || { printError "No such file: ${headerFile:?}"; exit 1; } ;;
esac
# Check the footer file.
case "${footerFile:?}" in
# If the file value equals "-", use stdin.
'-') footerFile="${tmpWorkDir:?}/footer"; cat <&0 > "${footerFile:?}" ;;
# If the file value equals "none", use an empty file.
'none') footerFile="${tmpWorkDir:?}/footer"; true > "${footerFile:?}" ;;
# If the file value equals "builtin", use the built-in value.
'builtin') footerFile="${tmpWorkDir:?}/footer"; printf -- '%s' "${HBLOCK_FOOTER_BUILTIN?}" > "${footerFile:?}" ;;
# If the file does not exist, throw an error.
*) [ -e "${footerFile:?}" ] || { printError "No such file: ${footerFile:?}"; exit 1; } ;;
esac
# Check the sources file.
case "${sourcesFile:?}" in
# If the file value equals "-", use stdin.
'-') sourcesFile="${tmpWorkDir:?}/sources.list"; cat <&0 > "${sourcesFile:?}" ;;
# If the file value equals "none", use an empty file.
'none') sourcesFile="${tmpWorkDir:?}/sources.list"; true > "${sourcesFile:?}" ;;
# If the file value equals "builtin", use the built-in value.
'builtin') sourcesFile="${tmpWorkDir:?}/sources.list"; printf -- '%s' "${HBLOCK_SOURCES_BUILTIN?}" > "${sourcesFile:?}" ;;
# If the file does not exist, throw an error.
*) [ -e "${sourcesFile:?}" ] || { printError "No such file: ${sourcesFile:?}"; exit 1; } ;;
esac
# Check the allowlist file.
case "${allowlistFile:?}" in
# If the file value equals "-", use stdin.
'-') allowlistFile="${tmpWorkDir:?}/allow.list"; cat <&0 > "${allowlistFile:?}" ;;
# If the file value equals "none", use an empty file.
'none') allowlistFile="${tmpWorkDir:?}/allow.list"; true > "${allowlistFile:?}" ;;
# If the file value equals "builtin", use the built-in value.
'builtin') allowlistFile="${tmpWorkDir:?}/allow.list"; printf -- '%s' "${HBLOCK_ALLOWLIST_BUILTIN?}" > "${allowlistFile:?}" ;;
# If the file does not exist, throw an error.
*) [ -e "${allowlistFile:?}" ] || { printError "No such file: ${allowlistFile:?}"; exit 1; } ;;
esac
# Check the denylist file.
case "${denylistFile:?}" in
# If the file value equals "-", use stdin.
'-') denylistFile="${tmpWorkDir:?}/deny.list"; cat <&0 > "${denylistFile:?}" ;;
# If the file value equals "none", use an empty file.
'none') denylistFile="${tmpWorkDir:?}/deny.list"; true > "${denylistFile:?}" ;;
# If the file value equals "builtin", use the built-in value.
'builtin') denylistFile="${tmpWorkDir:?}/deny.list"; printf -- '%s' "${HBLOCK_DENYLIST_BUILTIN?}" > "${denylistFile:?}" ;;
# If the file does not exist, throw an error.
*) [ -e "${denylistFile:?}" ] || { printError "No such file: ${denylistFile:?}"; exit 1; } ;;
esac
# Create an empty blocklist file.
blocklistFile="${tmpWorkDir:?}/block.list"
true > "${blocklistFile:?}"
# If the sources file is not empty, each source is downloaded and appended to the blocklist file.
if [ -s "${sourcesFile:?}" ]; then
printInfo 'Downloading sources'
# Read the sources file ignoring lines that start with "#" or are empty.
sed -e '/^#/d;/^$/d' -- "${sourcesFile:?}" | while IFS= read -r url || [ -n "${url?}" ]; do
printList "${url:?}"
if fetchUrl "${url:?}" > "${blocklistFile:?}.aux"; then
cat -- "${blocklistFile:?}.aux" >> "${blocklistFile:?}" \
&& rm -f -- "${blocklistFile:?}.aux"
elif [ "${continue:?}" = 'true' ]; then
printWarn "Cannot obtain source: ${url:?}"
else
printError "Cannot obtain source: ${url:?}"
exit 1
fi
done
fi
# If the denylist file is not empty, it is appended to the blocklist file.
if [ -s "${denylistFile:?}" ]; then
printInfo 'Applying denylist'
cat -- "${denylistFile:?}" >> "${blocklistFile:?}"
fi
# If the blocklist file is not empty, it is sanitized.
if [ -s "${blocklistFile:?}" ]; then
printInfo 'Sanitizing blocklist'
printList 'Removing carriage return'
tr -d '\r' \
< "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Transforming to lowercase'
awk '{print(tolower($0))}' \
< "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Removing comments'
sed -e 's/#.*//' \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Trimming spaces'
sed -e 's/^[[:blank:]]*//' \
-e 's/[[:blank:]]*$//' \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Matching hosts lines'
if [ "${lenient:?}" = 'true' ]; then
# This regex is not ideal as it matches technically invalid addresses, but it is POSIX-compliant.
ipv4Regex='\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\)\{0,1\}'
ipv6Regex='\(\([0-9a-f]\{0,4\}:\)\{1,7\}[0-9a-f]\{0,4\}\)\{0,1\}'
ipRegex="${ipv4Regex:?}${ipv6Regex:?}"
else
# This regex is not ideal as it matches technically invalid addresses, but it is POSIX-compliant.
ipv4Regex='\(0\.0\.0\.0\)\{0,1\}\(127\.0\.0\.1\)\{0,1\}'
ipv6Regex='\(::\)\{0,1\}\(::1\)\{0,1\}'
ipRegex="${ipv4Regex:?}${ipv6Regex:?}"
fi
domainRegex='\([0-9a-z_-]\{1,63\}\.\)\{1,\}[a-z][0-9a-z_-]\{1,62\}'
sed -ne '/^\('"${ipRegex:?}"'[[:blank:]]\{1,\}\)\{0,1\}'"${domainRegex:?}"'$/p' \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Removing reserved TLDs'
sed -e '/\.corp$/d' \
-e '/\.domain$/d' \
-e '/\.example$/d' \
-e '/\.home$/d' \
-e '/\.host$/d' \
-e '/\.invalid$/d' \
-e '/\.lan$/d' \
-e '/\.local$/d' \
-e '/\.localdomain$/d' \
-e '/\.localhost$/d' \
-e '/\.test$/d' \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Removing destination IPs'
sed -e 's/^.\{1,\}[[:blank:]]\{1,\}//' \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
printList 'Sorting entries'
sort -- "${blocklistFile:?}" | uniq | sed -e '/^$/d' > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
fi
# If the allowlist file is not empty, the entries on it are removed from the blocklist file.
if [ -s "${allowlistFile:?}" ]; then
printInfo 'Applying allowlist'
# Entries are treated as regexes depending on whether the regex option is enabled.
sed -e '/^#/d;/^$/d' -- "${allowlistFile:?}" >> "${blocklistFile:?}.pat"
if [ "${regex:?}" = 'true' ]; then
grep -vf "${blocklistFile:?}.pat" \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
else
grep -Fxvf "${blocklistFile:?}.pat" \
-- "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
fi
rm -f -- "${blocklistFile:?}.pat"
fi
# Count blocked domains.
blocklistCount="$(wc -l < "${blocklistFile:?}" | awk '{print($1)}')"
# If the blocklist file is not empty, the format template is applied.
if [ -s "${blocklistFile:?}" ]; then
printInfo 'Applying format template'
# The number of domains per line is equal to the value of the wrap option.
if [ "${wrap:?}" -gt '1' ]; then
awk -v FS=' ' -v RS='\n' -v W="${wrap:?}" '{ORS=(NR%W?FS:RS)}1;END{if(NR%W){printf(RS)}}' \
< "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
fi
# The following awk script replaces in the template the variables starting with a % sign with their value.
# Using the "gsub" method would be much simpler, but I have found that in some awk versions it performs very poorly.
awkTemplateScript="$(cat <<-'EOF'
BEGIN { split(T, A, ""); L = length(T); O = "" }
{
for (i = 1; i <= L; i++) {
if (A[i] == "%") {
i++; if (A[i] == "D") O = O $0
else if (A[i] == "R") O = O R
else if (A[i] == "%") O = O "%%"
} else { O = O A[i] }
}
printf("%s\n", O); O = ""
}
EOF
)"
awk -v T="${template?}" -v R="${redirection?}" "${awkTemplateScript:?}" \
< "${blocklistFile:?}" > "${blocklistFile:?}.aux" \
&& mv -f -- "${blocklistFile:?}.aux" "${blocklistFile:?}"
fi
printOutputFile() {
# Define "C" variable for convenience.
C="${comment?}"
# Append banner to the output file.
if [ -n "${C?}" ]; then
cat <<-EOF
${C?} Generated with: https://github.com/hectorm/hblock
${C?} Blocked domains: ${blocklistCount:?}
EOF
fi
# If the header file is not empty, it is appended to the output file.
if [ -s "${headerFile:?}" ]; then
[ -z "${C?}" ] || printf -- '\n%s\n' "${C?} BEGIN HEADER"
awk 1 < "${headerFile:?}"
[ -z "${C?}" ] || printf -- '%s\n' "${C?} END HEADER"
fi
# If the blocklist file is not empty, it is appended to the output file.
if [ -s "${blocklistFile:?}" ]; then
[ -z "${C?}" ] || printf -- '\n%s\n' "${C?} BEGIN BLOCKLIST"
awk 1 < "${blocklistFile:?}"
[ -z "${C?}" ] || printf -- '%s\n' "${C?} END BLOCKLIST"
fi
# If the footer file is not empty, it is appended to the output file.
if [ -s "${footerFile:?}" ]; then
[ -z "${C?}" ] || printf -- '\n%s\n' "${C?} BEGIN FOOTER"
awk 1 < "${footerFile:?}"
[ -z "${C?}" ] || printf -- '%s\n' "${C?} END FOOTER"
fi
}
# If the file value equals "-", print to stdout.
if [ "${outputFile:?}" = '-' ]; then
printOutputFile
# Try writing the file.
elif touch -- "${outputFile:?}" >/dev/null 2>&1; then
printOutputFile > "${outputFile:?}"
# If the writing fails, try with sudo.
elif exists sudo && exists tee; then
printOutputFile | sudo tee -- "${outputFile:?}" >/dev/null
# Throw an error for everything else.
else
printError "Cannot write file: ${outputFile:?}"
exit 1
fi
printInfo "${blocklistCount:?} blocked domains!"
}
main "${@-}"