-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathbasic-install.sh
More file actions
executable file
·2539 lines (2244 loc) · 96.9 KB
/
Copy pathbasic-install.sh
File metadata and controls
executable file
·2539 lines (2244 loc) · 96.9 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
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 bash
# Pi-hole: A black hole for Internet advertisements
# (c) Pi-hole (https://pi-hole.net)
# Network-wide ad blocking via your own hardware.
#
# Installs and Updates Pi-hole
#
# This file is copyright under the latest version of the EUPL.
# Please see LICENSE file for your rights under this license.
# pi-hole.net/donate
#
# Install with this command (from your Linux machine):
#
# curl -sSL https://install.pi-hole.net | bash
# -e option instructs bash to immediately exit if any command [1] has a non-zero exit status
# We do not want users to end up with a partially working install, so we exit the script
# instead of continuing the installation with something broken
set -e
# Append common folders to the PATH to ensure that all basic commands are available.
# When using "su" an incomplete PATH could be passed: https://github.com/pi-hole/pi-hole/issues/3209
export PATH+=':/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
# Trap any errors, then exit
trap abort INT QUIT TERM
######## VARIABLES #########
# For better maintainability, we store as much information that can change in variables
# This allows us to make a change in one place that can propagate to all instances of the variable
# These variables should all be GLOBAL variables, written in CAPS
# Local variables will be in lowercase and will exist only within functions
# It's still a work in progress, so you may see some variance in this guideline until it is complete
# Dialog result codes
# dialog code values can be set by environment variables, we only override if
# the env var is not set or empty.
: "${DIALOG_OK:=0}"
: "${DIALOG_CANCEL:=1}"
: "${DIALOG_ESC:=255}"
# List of supported DNS servers
DNS_SERVERS=$(
cat <<EOM
Google (ECS, DNSSEC);8.8.8.8;8.8.4.4;2001:4860:4860:0:0:0:0:8888;2001:4860:4860:0:0:0:0:8844
OpenDNS (ECS, DNSSEC);208.67.222.222;208.67.220.220;2620:119:35::35;2620:119:53::53
Level3;4.2.2.1;4.2.2.2;;
Comodo;8.26.56.26;8.20.247.20;;
Quad9 (filtered, DNSSEC);9.9.9.9;149.112.112.112;2620:fe::fe;2620:fe::9
Quad9 (unfiltered, no DNSSEC);9.9.9.10;149.112.112.10;2620:fe::10;2620:fe::fe:10
Quad9 (filtered, ECS, DNSSEC);9.9.9.11;149.112.112.11;2620:fe::11;2620:fe::fe:11
Cloudflare (DNSSEC);1.1.1.1;1.0.0.1;2606:4700:4700::1111;2606:4700:4700::1001
EOM
)
DNS_SERVERS_IPV6_ONLY=$(
cat <<EOM
Google (ECS, DNSSEC);2001:4860:4860:0:0:0:0:8888;2001:4860:4860:0:0:0:0:8844
OpenDNS (ECS, DNSSEC);2620:119:35::35;2620:119:53::53
Quad9 (filtered, DNSSEC);2620:fe::fe;2620:fe::9
Quad9 (unfiltered, no DNSSEC);2620:fe::10;2620:fe::fe:10
Quad9 (filtered, ECS, DNSSEC);2620:fe::11;2620:fe::fe:11
Cloudflare (DNSSEC);2606:4700:4700::1111;2606:4700:4700::1001
EOM
)
# Location for final installation log storage
installLogLoc="/etc/pihole/install.log"
# This is a file used for the colorized output
coltable="/opt/pihole/COL_TABLE"
# Root of the web server
webroot="/var/www/html"
# We clone (or update) two git repositories during the install. This helps to make sure that we always have the latest versions of the relevant files.
# web is used to set up the Web admin interface.
# Pi-hole contains various setup scripts and files which are critical to the installation.
# Search for "PI_HOLE_LOCAL_REPO" in this file to see all such scripts.
# Two notable scripts are gravity.sh (used to generate the HOSTS file) and advanced/Scripts/webpage.sh (used to install the Web admin interface)
webInterfaceGitUrl="https://github.com/pi-hole/web.git"
webInterfaceDir="${webroot}/admin"
piholeGitUrl="https://github.com/pi-hole/pi-hole.git"
PI_HOLE_LOCAL_REPO="/etc/.pihole"
# List of pihole scripts, stored in an array
PI_HOLE_FILES=(list piholeDebug piholeLogFlush setupLCD update version gravity uninstall webpage)
# This directory is where the Pi-hole scripts will be installed
PI_HOLE_INSTALL_DIR="/opt/pihole"
PI_HOLE_CONFIG_DIR="/etc/pihole"
PI_HOLE_BIN_DIR="/usr/local/bin"
PI_HOLE_V6_CONFIG="${PI_HOLE_CONFIG_DIR}/pihole.toml"
fresh_install=true
adlistFile="/etc/pihole/adlists.list"
# Pi-hole needs an IP address; to begin, these variables are empty since we don't know what the IP is until this script can run
IPV4_ADDRESS=
IPV6_ADDRESS=
# Give settings their default values. These may be changed by prompts later in the script.
QUERY_LOGGING=
PRIVACY_LEVEL=
PIHOLE_INTERFACE=
# Where old configs go to if a v6 migration is performed
V6_CONF_MIGRATION_DIR="/etc/pihole/migration_backup_v6"
if [ -z "${USER}" ]; then
USER="$(id -un)"
fi
# dialog dimensions: Let dialog handle appropriate sizing.
r=20
c=70
# Version of Pi-hole's meta package on APT based systems
# Must be incremented whenever dependencies in PIHOLE_META_PACKAGE_CONTROL_APT change
PIHOLE_META_VERSION_APT=0.7
# Content of Pi-hole's meta package control file on APT based systems
PIHOLE_META_PACKAGE_CONTROL_APT=$(
cat <<EOM
Package: pihole-meta
Version: ${PIHOLE_META_VERSION_APT}
Maintainer: Pi-hole team <adblock@pi-hole.net>
Architecture: all
Description: Pi-hole dependency meta package
Depends: awk,bash-completion,binutils,ca-certificates,cron|cron-daemon,curl,dialog,bind9-dnsutils|dnsutils,dns-root-data,git,grep,iproute2,iputils-ping,jq,libcap2,libcap2-bin,logrotate,lshw,procps,psmisc,sudo,unzip
Section: contrib/metapackages
Priority: optional
EOM
)
# Content of Pi-hole's meta package control file on RPM based systems
PIHOLE_META_PACKAGE_CONTROL_RPM=$(
cat <<EOM
Name: pihole-meta
Version: 0.4
Release: 1
License: EUPL
BuildArch: noarch
Summary: Pi-hole dependency meta package
Requires: bash-completion,bind-utils,binutils,ca-certificates,chkconfig,cronie,curl,dialog,findutils,gawk,git,grep,iproute,jq,libcap,logrotate,lshw,procps-ng,psmisc,sudo,unzip
%description
Pi-hole dependency meta package
%prep
%build
%files
%install
%changelog
* Thu Dec 18 2025 Pi-hole Team - 0.4
- Add logrotate to the list of dependencies
* Mon Jul 14 2025 Pi-hole Team - 0.3
- Remove nmap-ncat from the list of dependencies
* Wed May 28 2025 Pi-hole Team - 0.2
- Add gawk to the list of dependencies
* Sun Sep 29 2024 Pi-hole Team - 0.1
- First version being packaged
EOM
)
# List of required packages on APK based systems
PIHOLE_META_VERSION_APK=0.3
PIHOLE_META_DEPS_APK=(
bash
bash-completion
bind-tools
binutils
coreutils
cronie
curl
dialog
gawk
git
grep
iproute2-minimal # piholeARPTable.sh
iproute2-ss # piholeDebug.sh
jq
libcap
logrotate
lscpu # piholeDebug.sh
lshw # piholeDebug.sh
ncurses
procps-ng
psmisc
shadow
sudo
tzdata
unzip
)
######## Undocumented Flags. Shhh ########
# These are undocumented flags; some of which we can use when repairing an installation
# The runUnattended flag is one example of this
repair=false
runUnattended=false
# Check arguments for the undocumented flags
for var in "$@"; do
case "${var}" in
"--repair") repair=true ;;
"--unattended") runUnattended=true ;;
esac
done
# If the color table file exists,
if [[ -f "${coltable}" ]]; then
# source it
# shellcheck source="./advanced/Scripts/COL_TABLE"
source "${coltable}"
# Otherwise,
else
# Set these values so the installer can still run in color
COL_NC='\e[0m' # No Color
COL_GREEN='\e[1;32m'
COL_RED='\e[1;31m'
TICK="[${COL_GREEN}✓${COL_NC}]"
CROSS="[${COL_RED}✗${COL_NC}]"
INFO="[i]"
OVER="\\r\\033[K"
fi
# A simple function that just echoes out our logo in ASCII format
# This lets users know that it is a Pi-hole, LLC product
show_ascii_berry() {
echo -e "
${COL_GREEN}.;;,.
.ccccc:,.
:cccclll:. ..,,
:ccccclll. ;ooodc
'ccll:;ll .oooodc
.;cll.;;looo:.
${COL_RED}.. ','.
.',,,,,,'.
.',,,,,,,,,,.
.',,,,,,,,,,,,....
....''',,,,,,,'.......
......... .... .........
.......... ..........
.......... ..........
......... .... .........
........,,,,,,,'......
....',,,,,,,,,,,,.
.',,,,,,,,,'.
.',,,,,,'.
..'''.${COL_NC}
"
}
abort() {
# remove any leftover build directory that may exist
rm -rf /tmp/pihole-meta_*
echo -e "\\n\\n ${COL_RED}Installation was interrupted${COL_NC}\\n"
echo -e "Pi-hole's dependencies might be already installed. If you want to remove them you can try to\\n"
echo -e "a) run 'pihole uninstall' \\n"
echo -e "b) Remove the meta-package 'pihole-meta' manually \\n"
echo -e "E.g. sudo apt-get remove pihole-meta && apt-get autoremove \\n"
exit 1
}
is_command() {
# Checks to see if the given command (passed as a string argument) exists on the system.
# The function returns 0 (success) if the command exists, and 1 if it doesn't.
local check_command="$1"
command -v "${check_command}" >/dev/null 2>&1
}
check_fresh_install() {
# in case of an update (can be a v5 -> v6 or v6 -> v6 update) or repair
if [[ -f "${PI_HOLE_V6_CONFIG}" ]] || [[ -f "/etc/pihole/setupVars.conf" ]]; then
fresh_install=false
fi
}
# Compatibility
package_manager_detect() {
# First check to see if apt-get is installed.
if is_command apt-get; then
# Set some global variables here
# We don't set them earlier since the installed package manager might be rpm, so these values would be different
PKG_MANAGER="apt-get"
# A variable to store the command used to update the package cache
UPDATE_PKG_CACHE="${PKG_MANAGER} update"
# The command we will use to actually install packages
PKG_INSTALL="${PKG_MANAGER} -qq --no-install-recommends install"
# The command we will use to remove packages (used in the uninstaller)
PKG_REMOVE="${PKG_MANAGER} -y remove --purge"
# If apt-get is not found, check for rpm.
elif is_command rpm; then
# Then check if dnf or yum is the package manager
if is_command dnf; then
PKG_MANAGER="dnf"
else
PKG_MANAGER="yum"
fi
# These variable names match the ones for apt-get. See above for an explanation of what they are for.
PKG_INSTALL="${PKG_MANAGER} install -y"
# The command we will use to remove packages (used in the uninstaller)
PKG_REMOVE="${PKG_MANAGER} remove -y"
# If neither apt-get or yum/dnf package managers were found, check for apk.
elif is_command apk; then
PKG_MANAGER="apk"
UPDATE_PKG_CACHE="${PKG_MANAGER} update"
PKG_INSTALL="${PKG_MANAGER} add"
PKG_REMOVE="${PKG_MANAGER} del"
else
# we cannot install required packages
printf " %b No supported package manager found\\n" "${CROSS}"
# so exit the installer
exit 1
fi
}
build_dependency_package(){
# This function will build a package that contains all the dependencies needed for Pi-hole
if is_command apk ; then
local str="APK based system detected. Dependencies will be installed using a virtual package named pihole-meta"
printf " %b %s...\\n" "${INFO}" "${str}"
return 0
fi
# remove any leftover build directory that may exist
rm -rf /tmp/pihole-meta_*
# Create a fresh build directory with random name
# Busybox Compat: `mktemp` long flags unsupported
# -d flag is short form of --directory
local tempdir
tempdir="$(mktemp -d /tmp/pihole-meta_XXXXX)"
chmod 0755 "${tempdir}"
if is_command apt-get; then
# move into the tmp directory
pushd /tmp &>/dev/null || return 1
# remove leftover package if it exists from previous runs
rm -f /tmp/pihole-meta.deb
# Prepare directory structure and control file
mkdir -p "${tempdir}"/DEBIAN
chmod 0755 "${tempdir}"/DEBIAN
touch "${tempdir}"/DEBIAN/control
# Write the control file
echo "${PIHOLE_META_PACKAGE_CONTROL_APT}" > "${tempdir}"/DEBIAN/control
# Build the package
local str="Building dependency package pihole-meta.deb"
printf " %b %s..." "${INFO}" "${str}"
if dpkg-deb --build --root-owner-group "${tempdir}" pihole-meta.deb &>/dev/null; then
printf "%b %b %s\\n" "${OVER}" "${TICK}" "${str}"
else
printf "%b %b %s\\n" "${OVER}" "${CROSS}" "${str}"
printf "%b Error: Building pihole-meta.deb failed. %b\\n" "${COL_RED}" "${COL_NC}"
return 1
fi
# Move back into the directory the user started in
popd &> /dev/null || return 1
elif is_command rpm; then
# move into the tmp directory
pushd /tmp &>/dev/null || return 1
# remove leftover package if it exists from previous runs
rm -f /tmp/pihole-meta.rpm
# Prepare directory structure and spec file
mkdir -p "${tempdir}"/SPECS
touch "${tempdir}"/SPECS/pihole-meta.spec
echo "${PIHOLE_META_PACKAGE_CONTROL_RPM}" > "${tempdir}"/SPECS/pihole-meta.spec
# check if we need to install the build dependencies
if ! is_command rpmbuild; then
local REMOVE_RPM_BUILD=true
eval "${PKG_INSTALL}" "rpm-build"
fi
# Build the package
local str="Building dependency package pihole-meta.rpm"
printf " %b %s..." "${INFO}" "${str}"
if rpmbuild -bb "${tempdir}"/SPECS/pihole-meta.spec --define "_topdir ${tempdir}" &>/dev/null; then
printf "%b %b %s\\n" "${OVER}" "${TICK}" "${str}"
else
printf "%b %b %s\\n" "${OVER}" "${CROSS}" "${str}"
printf "%b Error: Building pihole-meta.rpm failed. %b\\n" "${COL_RED}" "${COL_NC}"
return 1
fi
# Move the package to the /tmp directory
mv "${tempdir}"/RPMS/noarch/pihole-meta*.rpm /tmp/pihole-meta.rpm
# Remove the build dependencies when we've installed them
if [ -n "${REMOVE_RPM_BUILD}" ]; then
eval "${PKG_REMOVE}" "rpm-build"
fi
# Move back into the directory the user started in
popd &> /dev/null || return 1
# If neither apt-get or yum/dnf package managers were found
else
# we cannot build required packages
printf " %b No supported package manager found\\n" "${CROSS}"
# so exit the installer
exit 1
fi
# Remove the build directory
rm -rf "${tempdir}"
}
# A function for checking if a directory is a git repository
is_repo() {
# Use a named, local variable instead of the vague $1, which is the first argument passed to this function
# These local variables should always be lowercase
local directory="${1}"
# A variable to store the return code
local rc
# If the first argument passed to this function is a directory,
if [[ -d "${directory}" ]]; then
# move into the directory
pushd "${directory}" &>/dev/null || return 1
# Use git to check if the directory is a repo
# git -C is not used here to support git versions older than 1.8.4
git status --short &> /dev/null || rc=$?
# Move back into the directory the user started in
popd &> /dev/null || return 1
else
# Set a non-zero return code if directory does not exist
rc=1
fi
# Return the code; if one is not set, return 0
return "${rc:-0}"
}
# A function to clone a repo
make_repo() {
# Set named variables for better readability
local directory="${1}"
local remoteRepo="${2}"
# The message to display when this function is running
str="Clone ${remoteRepo} into ${directory}"
# Display the message and use the color table to preface the message with an "info" indicator
printf " %b %s..." "${INFO}" "${str}"
# If the directory exists,
if [[ -d "${directory}" ]]; then
# Return with a 1 to exit the installer. We don't want to overwrite what could already be here in case it is not ours
str="Unable to clone ${remoteRepo} into ${directory} : Directory already exists"
printf "%b %b%s\\n" "${OVER}" "${CROSS}" "${str}"
return 1
fi
# Clone the repo and return the return code from this command
git clone -q --depth 20 "${remoteRepo}" "${directory}" &>/dev/null || return $?
# Move into the directory that was passed as an argument
pushd "${directory}" &>/dev/null || return 1
# Check current branch. If it is master, then reset to the latest available tag.
# In case extra commits have been added after tagging/release (i.e in case of metadata updates/README.MD tweaks)
curBranch=$(git rev-parse --abbrev-ref HEAD)
if [[ "${curBranch}" == "master" ]]; then
# If we're calling make_repo() then it should always be master, we may not need to check.
git reset --hard "$(git describe --abbrev=0 --tags)" || return $?
fi
# Show a colored message showing it's status
printf "%b %b %s\\n" "${OVER}" "${TICK}" "${str}"
# Data in the repositories is public anyway so we can make it readable by everyone (+r to keep executable permission if already set by git)
chmod -R a+rX "${directory}"
# Move back into the original directory
popd &>/dev/null || return 1
return 0
}
# We need to make sure the repos are up-to-date so we can effectively install Clean out the directory if it exists for git to clone into
update_repo() {
# Use named, local variables
# As you can see, these are the same variable names used in the last function,
# but since they are local, their scope does not go beyond this function
# This helps prevent the wrong value from being assigned if you were to set the variable as a GLOBAL one
local directory="${1}"
local curBranch
# A variable to store the message we want to display;
# Again, it's useful to store these in variables in case we need to reuse or change the message;
# we only need to make one change here
local str="Update repo in ${1}"
# Move into the directory that was passed as an argument
pushd "${directory}" &>/dev/null || return 1
# Let the user know what's happening
printf " %b %s..." "${INFO}" "${str}"
# Stash any local commits as they conflict with our working code
git stash --all --quiet &>/dev/null || true # Okay for stash failure
git clean --quiet --force -d || true # Okay for already clean directory
# Pull the latest commits
git pull --no-rebase --quiet &>/dev/null || return $?
# Check current branch. If it is master, then reset to the latest available tag.
# In case extra commits have been added after tagging/release (i.e in case of metadata updates/README.MD tweaks)
curBranch=$(git rev-parse --abbrev-ref HEAD)
if [[ "${curBranch}" == "master" ]]; then
git reset --hard "$(git describe --abbrev=0 --tags)" || return $?
fi
# Show a completion message
printf "%b %b %s\\n" "${OVER}" "${TICK}" "${str}"
# Data in the repositories is public anyway so we can make it readable by everyone (+r to keep executable permission if already set by git)
chmod -R a+rX "${directory}"
# Move back into the original directory
popd &>/dev/null || return 1
return 0
}
# A function that combines the previous git functions to update or clone a repo
getGitFiles() {
# Setup named variables for the git repos
# We need the directory
local directory="${1}"
# as well as the repo URL
local remoteRepo="${2}"
# A local variable containing the message to be displayed
local str="Check for existing repository in ${1}"
# Show the message
printf " %b %s..." "${INFO}" "${str}"
# Check if the directory is a repository
if is_repo "${directory}"; then
# Show that we're checking it
printf "%b %b %s\\n" "${OVER}" "${TICK}" "${str}"
# Update the repo, returning an error message on failure
update_repo "${directory}" || {
printf "\\n %b: Could not update local repository. Contact support.%b\\n" "${COL_RED}" "${COL_NC}"
exit 1
}
# If it's not a .git repo,
else
# Show an error
printf "%b %b %s\\n" "${OVER}" "${CROSS}" "${str}"
# Attempt to make the repository, showing an error on failure
make_repo "${directory}" "${remoteRepo}" || {
printf "\\n %bError: Could not update local repository. Contact support.%b\\n" "${COL_RED}" "${COL_NC}"
exit 1
}
fi
echo ""
# Success via one of the two branches, as the commands would exit if they failed.
return 0
}
# Reset a repo to get rid of any local changed
resetRepo() {
# Use named variables for arguments
local directory="${1}"
# Move into the directory
pushd "${directory}" &>/dev/null || return 1
# Store the message in a variable
str="Resetting repository within ${1}..."
# Show the message
printf " %b %s..." "${INFO}" "${str}"
# Use git to remove the local changes
git reset --hard &>/dev/null || return $?
# Data in the repositories is public anyway so we can make it readable by everyone (+r to keep executable permission if already set by git)
chmod -R a+rX "${directory}"
# And show the status
printf "%b %b %s\\n" "${OVER}" "${TICK}" "${str}"
# Return to where we came from
popd &>/dev/null || return 1
# Function succeeded, as "git reset" would have triggered a return earlier if it failed
return 0
}
find_IPv4_information() {
# Detects IPv4 address used for communication to WAN addresses.
# Accepts no arguments, returns no values.
# Named, local variables
local route
local IPv4bare
# Find IP used to route to outside world by checking the route to Google's public DNS server
if ! route="$(ip route get 8.8.8.8 2> /dev/null)"; then
printf " %b No IPv4 route was detected.\n" "${INFO}"
IPV4_ADDRESS=""
return
fi
# Get just the interface IPv4 address
# shellcheck disable=SC2059,SC2086
# disabled as we intentionally want to split on whitespace and have printf populate
# the variable with just the first field.
printf -v IPv4bare "$(printf ${route#*src })"
if ! valid_ip "${IPv4bare}"; then
IPv4bare="127.0.0.1"
fi
# Append the CIDR notation to the IP address, if valid_ip fails this should return 127.0.0.1/8
IPV4_ADDRESS=$(ip -oneline -family inet address show | grep "${IPv4bare}/" | awk '{print $4}' | awk 'END {print}')
}
confirm_ipv6_only() {
# Confirm from user before IPv6 only install
dialog --no-shadow --output-fd 1 \
--no-button "Exit" --yes-button "Install IPv6 ONLY" \
--yesno "\\n\\nWARNING - no valid IPv4 route detected.\\n\\n\
This may be due to a temporary connectivity issue,\\n\
or you may be installing on an IPv6 only system.\\n\\n\
Do you wish to continue with an IPv6-only installation?\\n\\n" \
"${r}" "${c}" && result=0 || result="$?"
case "${result}" in
"${DIALOG_CANCEL}" | "${DIALOG_ESC}")
printf " %b Installer exited at IPv6 only message.\\n" "${INFO}"
exit 1
;;
esac
DNS_SERVERS="${DNS_SERVERS_IPV6_ONLY}"
printf " %b Proceeding with IPv6 only installation.\\n" "${INFO}"
}
# Get available interfaces that are UP
get_available_interfaces() {
# There may be more than one so it's all stored in a variable
# The ip command list all interfaces that are in the up state
# The awk command filters out any interfaces that have the LOOPBACK flag set
# while using the characters ": " or "@" as a field separator for awk
availableInterfaces=$(ip --oneline link show up | awk -F ': |@' '!/<.*LOOPBACK.*>/ {print $2}')
}
# A function for displaying the dialogs the user sees when first running the installer
welcomeDialogs() {
# Display the welcome dialog using an appropriately sized window via the calculation conducted earlier in the script
dialog --no-shadow --clear --keep-tite \
--backtitle "Welcome" \
--title "Pi-hole Automated Installer" \
--msgbox "\\n\\nThis installer will transform your device into a network-wide ad blocker!" \
"${r}" "${c}" \
--and-widget --clear \
--backtitle "Support Pi-hole" \
--title "Open Source Software" \
--msgbox "\\n\\nThe Pi-hole is free, but powered by your donations: https://pi-hole.net/donate/" \
"${r}" "${c}" \
--and-widget --clear \
--colors \
--backtitle "Initiating network interface" \
--title "Static IP Needed" \
--no-button "Exit" --yes-button "Continue" \
--defaultno \
--yesno "\\n\\nThe Pi-hole is a SERVER so it needs a STATIC IP ADDRESS to function properly.\\n\\n\
\\Zb\\Z1IMPORTANT:\\Zn If you have not already done so, you must ensure that this device has a static IP.\\n\\n\
Depending on your operating system, there are many ways to achieve this, through DHCP reservation, or by manually assigning one.\\n\\n\
Please continue when the static addressing has been configured." \
"${r}" "${c}" && result=0 || result="$?"
case "${result}" in
"${DIALOG_CANCEL}" | "${DIALOG_ESC}")
printf " %b Installer exited at static IP message.\\n" "${INFO}"
exit 1
;;
esac
}
# A function that lets the user pick an interface to use with Pi-hole
chooseInterface() {
# Turn the available interfaces into a string so it can be used with dialog
local interfacesList
# Number of available interfaces
local interfaceCount
# POSIX compliant way to get the number of elements in an array
interfaceCount=$(printf "%s\n" "${availableInterfaces}" | wc -l)
# If there is one interface,
if [[ "${interfaceCount}" -eq 1 ]]; then
# Set it as the interface to use since there is no other option
PIHOLE_INTERFACE="${availableInterfaces}"
# Otherwise,
else
# Set status for the first entry to be selected
status="ON"
# While reading through the available interfaces
for interface in ${availableInterfaces}; do
# Put all these interfaces into a string
interfacesList="${interfacesList}${interface} available ${status} "
# All further interfaces are deselected
status="OFF"
done
# Disable check for double quote here as we are passing a string with spaces
# shellcheck disable=SC2086
PIHOLE_INTERFACE=$(dialog --no-shadow --keep-tite --output-fd 1 \
--cancel-label "Exit" --ok-label "Select" \
--radiolist "Choose An Interface (press space to toggle selection)" \
${r} ${c} "${interfaceCount}" ${interfacesList})
result=$?
case ${result} in
"${DIALOG_CANCEL}" | "${DIALOG_ESC}")
# Show an error message and exit
printf " %b %s\\n" "${CROSS}" "No interface selected, exiting installer"
exit 1
;;
esac
printf " %b Using interface: %s\\n" "${INFO}" "${PIHOLE_INTERFACE}"
fi
}
# This lets us prefer ULA addresses over GUA
# This caused problems for some users when their ISP changed their IPv6 addresses
# See https://github.com/pi-hole/pi-hole/issues/1473#issuecomment-301745953
testIPv6() {
# first will contain fda2 (ULA)
printf -v first "%s" "${1%%:*}"
# value1 will contain 253 which is the decimal value corresponding to 0xFD
value1=$(((0x${first}) / 256))
# value2 will contain 162 which is the decimal value corresponding to 0xA2
value2=$(((0x${first}) % 256))
# the ULA test is testing for fc00::/7 according to RFC 4193
if (((value1 & 254) == 252)); then
# echoing result to calling function as return value
echo "ULA"
fi
# the GUA test is testing for 2000::/3 according to RFC 4291
if (((value1 & 112) == 32)); then
# echoing result to calling function as return value
echo "GUA"
fi
# the LL test is testing for fe80::/10 according to RFC 4193
if (((value1) == 254)) && (((value2 & 192) == 128)); then
# echoing result to calling function as return value
echo "Link-local"
fi
}
find_IPv6_information() {
# Detects IPv6 address used for communication to WAN addresses.
mapfile -t IPV6_ADDRESSES <<<"$(ip -6 address | grep 'scope global' | awk '{print $2}')"
# For each address in the array above, determine the type of IPv6 address it is
for i in "${IPV6_ADDRESSES[@]}"; do
# Check if it's ULA, GUA, or LL by using the function created earlier
result=$(testIPv6 "${i}")
# If it's a ULA address, use it and store it as a global variable
[[ "${result}" == "ULA" ]] && ULA_ADDRESS="${i%/*}"
# If it's a GUA address, use it and store it as a global variable
[[ "${result}" == "GUA" ]] && GUA_ADDRESS="${i%/*}"
# Else if it's a Link-local address, we cannot use it, so just continue
done
# Determine which address to be used: Prefer ULA over GUA or don't use any if none found
# If the ULA_ADDRESS contains a value,
if [[ -n "${ULA_ADDRESS}" ]]; then
# set the IPv6 address to the ULA address
IPV6_ADDRESS="${ULA_ADDRESS}"
# Show this info to the user
printf " %b Found IPv6 ULA address\\n" "${INFO}"
# Otherwise, if the GUA_ADDRESS has a value,
elif [[ -n "${GUA_ADDRESS}" ]]; then
# Let the user know
printf " %b Found IPv6 GUA address\\n" "${INFO}"
# And assign it to the global variable
IPV6_ADDRESS="${GUA_ADDRESS}"
# If none of those work,
else
printf " %b Unable to find IPv6 ULA/GUA address\\n" "${INFO}"
# So set the variable to be empty
IPV6_ADDRESS=""
fi
}
# A function to collect IPv4 and IPv6 information of the device
collect_v4andv6_information() {
find_IPv4_information
printf " %b IPv4 address: %s\\n" "${INFO}" "${IPV4_ADDRESS}"
find_IPv6_information
printf " %b IPv6 address: %s\\n" "${INFO}" "${IPV6_ADDRESS}"
if [ "${IPV4_ADDRESS}" == "" ] && [ "${IPV6_ADDRESS}" != "" ]; then
confirm_ipv6_only
fi
}
# Check an IP address to see if it is a valid one
valid_ip() {
# Local, named variables
local ip=${1}
local stat=1
# Regex matching one IPv4 component, i.e. an integer from 0 to 255.
# See https://tools.ietf.org/html/rfc1340
local ipv4elem="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)"
# Regex matching an optional port (starting with '#') range of 1-65536
local portelem="(#(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}|0))?"
# Build a full IPv4 regex from the above subexpressions
local regex="^${ipv4elem}\\.${ipv4elem}\\.${ipv4elem}\\.${ipv4elem}${portelem}$"
# Evaluate the regex, and return the result
[[ ${ip} =~ ${regex} ]]
stat=$?
return "${stat}"
}
valid_ip6() {
local ip=${1}
local stat=1
# Regex matching one IPv6 element, i.e. a hex value from 0000 to FFFF
local ipv6elem="[0-9a-fA-F]{1,4}"
# Regex matching an IPv6 CIDR, i.e. 1 to 128
local v6cidr="(\\/([1-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])){0,1}"
# Regex matching an optional port (starting with '#') range of 1-65536
local portelem="(#(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}|0))?"
# Build a full IPv6 regex from the above subexpressions
local regex="^(((${ipv6elem}))*((:${ipv6elem}))*::((${ipv6elem}))*((:${ipv6elem}))*|((${ipv6elem}))((:${ipv6elem})){7})${v6cidr}${portelem}$"
# Evaluate the regex, and return the result
[[ ${ip} =~ ${regex} ]]
stat=$?
return "${stat}"
}
# A function to choose the upstream DNS provider(s)
setDNS() {
# Local, named variables
local DNSSettingsCorrect
# In an array, list the available upstream providers
DNSChooseOptions=()
local DNSServerCount=0
# Save the old Internal Field Separator in a variable,
OIFS=${IFS}
# and set the new one to newline
IFS=$'\n'
# Put the DNS Servers into an array
for DNSServer in ${DNS_SERVERS}; do
DNSName="$(cut -d';' -f1 <<<"${DNSServer}")"
DNSChooseOptions[DNSServerCount]="${DNSName}"
((DNSServerCount = DNSServerCount + 1))
DNSChooseOptions[DNSServerCount]=""
((DNSServerCount = DNSServerCount + 1))
done
DNSChooseOptions[DNSServerCount]="Custom"
((DNSServerCount = DNSServerCount + 1))
DNSChooseOptions[DNSServerCount]=""
# Restore the IFS to what it was
IFS=${OIFS}
# In a dialog, show the options
DNSchoices=$(dialog --no-shadow --keep-tite --output-fd 1 \
--cancel-label "Exit" \
--menu "Select Upstream DNS Provider. To use your own, select Custom." "${r}" "${c}" 7 \
"${DNSChooseOptions[@]}")
result=$?
case ${result} in
"${DIALOG_CANCEL}" | "${DIALOG_ESC}")
printf " %b Cancel was selected, exiting installer%b\\n" "${COL_RED}" "${COL_NC}"
exit 1
;;
esac
# Depending on the user's choice, set the GLOBAL variables to the IP of the respective provider
if [[ "${DNSchoices}" == "Custom" ]]; then
# Loop until we have a valid DNS setting
until [[ "${DNSSettingsCorrect}" = True ]]; do
# Signal value, to be used if the user inputs an invalid IP address
strInvalid="Invalid"
# Prepopulate the dialog with any previously set DNS values
prePopulate=""
i=1
while true; do
varname="PIHOLE_DNS_${i}"
[[ -n "${!varname}" ]] || break
[[ -n "${prePopulate}" ]] && prePopulate+=", "
prePopulate+="${!varname}"
((i++))
done
# Prompt the user to enter custom upstream servers
piholeDNS=$(dialog --no-shadow --keep-tite --output-fd 1 \
--cancel-label "Exit" \
--backtitle "Specify Upstream DNS Provider(s)" \
--inputbox "Enter your desired upstream DNS provider(s), separated by a comma.\
If you want to specify a port other than 53, separate it with a hash.\
\\n\\nFor example '8.8.8.8, 8.8.4.4' or '127.0.0.1#5335'" \
"${r}" "${c}" "${prePopulate}")
result=$?
case ${result} in
"${DIALOG_CANCEL}" | "${DIALOG_ESC}")
printf " %b Cancel was selected, exiting installer%b\\n" "${COL_RED}" "${COL_NC}"
exit 1
;;
esac
# Clean user input: replace whitespace with comma, then collapse consecutive commas.
piholeDNS="${piholeDNS//[[:blank:]]/,}"
while [[ "${piholeDNS}" == *,,* ]]; do piholeDNS="${piholeDNS//,,/,}"; done
piholeDNS="${piholeDNS#,}"
piholeDNS="${piholeDNS%,}"
# Clear any previously set PIHOLE_DNS_N variables before re-assigning.
i=1
while true; do
varname="PIHOLE_DNS_${i}"
[[ -n "${!varname}" ]] || break
unset "${varname}"
((i++))
done
# Split the cleaned input on commas and assign each entry to PIHOLE_DNS_N.
IFS=',' read -ra dns_array <<< "${piholeDNS}"
i=1
for entry in "${dns_array[@]}"; do
[[ -z "${entry}" ]] && continue
printf -v "PIHOLE_DNS_${i}" "%s" "${entry}"
((i++))
done
# Validate each DNS entry; build a list of invalid values.
invalidList=""
i=1
while true; do
varname="PIHOLE_DNS_${i}"
val="${!varname}"
[[ -n "${val}" ]] || break
if ! valid_ip "${val}" && ! valid_ip6 "${val}"; then
printf -v "${varname}" "%s" "${strInvalid}"
invalidList+=" ${val},"
fi
((i++))
done
# Require at least one DNS server to have been entered.
if [[ -z "${PIHOLE_DNS_1}" ]]; then
PIHOLE_DNS_1="${strInvalid}"
invalidList+=" (none),"
fi
# Remove trailing comma from list.
invalidList="${invalidList%,}"
# If any entries were invalid, explain to the user and retry.
if [[ -n "${invalidList}" ]]; then
dialog --no-shadow --keep-tite \
--title "Invalid IP Address(es)" \
--backtitle "Invalid IP" \
--msgbox "\\nOne or more of the entered IP addresses were invalid. Please try again.\
\\n\\nInvalid IPs:${invalidList}" \
"${r}" "${c}"
# Keep valid entries and discard invalid ones, then re-compact the numbering.
valid_entries=()
i=1
while true; do
varname="PIHOLE_DNS_${i}"
val="${!varname}"
[[ -n "${val}" ]] || break
if [[ "${val}" != "${strInvalid}" ]]; then
valid_entries+=("${val}")
fi
unset "${varname}"
((i++))
done
for i in "${!valid_entries[@]}"; do
printf -v "PIHOLE_DNS_$((i + 1))" "%s" "${valid_entries[${i}]}"
done
DNSSettingsCorrect=False
else
# Build confirmation message listing every DNS server.
local confirmDNSMsg="Are these settings correct?\\n"
i=1
while true; do
varname="PIHOLE_DNS_${i}"
val="${!varname}"
[[ -n "${val}" ]] || break
confirmDNSMsg+=$'\t'"DNS Server ${i}:"$'\t'"${val}\\n"
((i++))
done
dialog --no-shadow --no-collapse --keep-tite \
--backtitle "Specify Upstream DNS Provider(s)" \
--title "Upstream DNS Provider(s)" \
--yesno "${confirmDNSMsg}" \
"${r}" "${c}" && result=0 || result=$?
case ${result} in
"${DIALOG_OK}")
DNSSettingsCorrect=True
;;
"${DIALOG_CANCEL}")
DNSSettingsCorrect=False