1
0
mirror of https://github.com/pi-hole/pi-hole synced 2024-11-17 21:59:55 +00:00

Merge pull request #831 from airencracken/development

Consistent Style in Bash
This commit is contained in:
Adam Warner 2016-10-23 20:03:30 +01:00 committed by GitHub
commit 1f0ae16216
12 changed files with 1090 additions and 1134 deletions

View File

@ -47,119 +47,117 @@ domToRemoveList=()
piholeIPfile=/etc/pihole/piholeIP
piholeIPv6file=/etc/pihole/.useIPv6
if [[ -f ${piholeIPfile} ]];then
# If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIP=$(cat ${piholeIPfile})
#rm $piholeIPfile
if [[ -f ${piholeIPfile} ]]; then
# If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIP=$(cat ${piholeIPfile})
#rm $piholeIPfile
else
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*}
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*}
fi
modifyHost=false
# After setting defaults, check if there's local overrides
if [[ -r ${piholeDir}/pihole.conf ]];then
echo "::: Local calibration requested..."
. ${piholeDir}/pihole.conf
if [[ -r ${piholeDir}/pihole.conf ]]; then
echo "::: Local calibration requested..."
. ${piholeDir}/pihole.conf
fi
if [[ -f ${piholeIPv6file} ]];then
# If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
if [[ -f ${piholeIPv6file} ]]; then
# If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
fi
HandleOther() {
#check validity of domain
validDomain=$(echo "$1" | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/')
if [ -z "$validDomain" ]; then
echo "::: $1 is not a valid argument or domain name"
#check validity of domain
validDomain=$(echo "${1}" | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/')
if [ -z "${validDomain}" ]; then
echo "::: ${1} is not a valid argument or domain name"
else
domList=("${domList[@]}" ${validDomain})
domList=("${domList[@]}" ${validDomain})
fi
}
PopBlacklistFile() {
#check blacklist file exists, and if not, create it
if [[ ! -f ${blacklist} ]];then
touch ${blacklist}
if [[ ! -f ${blacklist} ]]; then
touch ${blacklist}
fi
for dom in "${domList[@]}"; do
if "$addmode"; then
AddDomain "$dom"
else
RemoveDomain "$dom"
fi
if "${addmode}"; then
AddDomain "${dom}"
else
RemoveDomain "${dom}"
fi
done
}
AddDomain() {
#| sed 's/\./\\./g'
#| sed 's/\./\\./g'
bool=false
grep -Ex -q "$1" ${blacklist} || bool=true
if ${bool}; then
#domain not found in the blacklist file, add it!
if ${verbose}; then
echo -n "::: Adding $1 to blacklist file..."
fi
echo "$1" >> ${blacklist}
#domain not found in the blacklist file, add it!
if ${verbose}; then
echo -n "::: Adding $1 to blacklist file..."
fi
echo "${1}" >> ${blacklist}
modifyHost=true
echo " done!"
else
if ${verbose}; then
echo "::: $1 already exists in $blacklist! No need to add"
echo "::: ${1} already exists in ${blacklist}! No need to add"
fi
fi
}
RemoveDomain() {
bool=false
grep -Ex -q "$1" ${blacklist} || bool=true
if ${bool}; then
#Domain is not in the blacklist file, no need to Remove
if ${verbose}; then
echo "::: $1 is NOT blacklisted! No need to remove"
fi
else
#Domain is in the blacklist file, add to a temporary array
if ${verbose}; then
echo "::: Un-blacklisting $dom..."
fi
domToRemoveList=("${domToRemoveList[@]}" $1)
modifyHost=true
fi
bool=false
grep -Ex -q "$1" ${blacklist} || bool=true
if ${bool}; then
#Domain is not in the blacklist file, no need to Remove
if ${verbose}; then
echo "::: $1 is NOT blacklisted! No need to remove"
fi
else
#Domain is in the blacklist file, add to a temporary array
if ${verbose}; then
echo "::: Un-blacklisting ${dom}..."
fi
domToRemoveList=("${domToRemoveList[@]}" $1)
modifyHost=true
fi
}
ModifyHostFile() {
if ${addmode}; then
#add domains to the hosts file
if [[ -r ${blacklist} ]];then
numberOf=$(cat ${blacklist} | sed '/^\s*$/d' | wc -l)
plural=; [[ "$numberOf" != "1" ]] && plural=s
echo ":::"
echo -n "::: Modifying HOSTS file to blacklist $numberOf domain${plural}..."
if [[ -n ${piholeIPv6} ]];then
if ${addmode}; then
#add domains to the hosts file
if [[ -r ${blacklist} ]]; then
numberOf=$(cat ${blacklist} | sed '/^\s*$/d' | wc -l)
plural=; [[ "${numberOf}" != "1" ]] && plural=s
echo ":::"
echo -n "::: Modifying HOSTS file to blacklist $numberOf domain${plural}..."
if [[ -n ${piholeIPv6} ]]; then
cat ${blacklist} | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> ${adList}
else
else
cat ${blacklist} | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >>${adList}
fi
fi
else
fi
fi
else
echo ":::"
for dom in "${domToRemoveList[@]}"
do
#we need to remove the domains from the blacklist file and the host file
echo "::: $dom"
for dom in "${domToRemoveList[@]}"; do
#we need to remove the domains from the blacklist file and the host file
echo "::: ${dom}"
echo -n "::: removing from HOSTS file..."
echo "$dom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /[^.]'{}'(?!.)/;' ${adList}
echo " done!"
echo -n "::: removing from blackist.txt..."
echo "$dom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' ${blacklist}
echo " done!"
echo "${dom}" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /[^.]'{}'(?!.)/;' ${adList}
echo " done!"
echo -n "::: removing from blackist.txt..."
echo "${dom}" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' ${blacklist}
echo " done!"
done
fi
}
@ -169,22 +167,22 @@ Reload() {
echo ":::"
echo -n "::: Refresh lists in dnsmasq..."
dnsmasqPid=$(pidof dnsmasq)
dnsmasqPid=$(pidof dnsmasq)
if [[ ${dnsmasqPid} ]]; then
# service already running - reload config
if [ -x "$(command -v systemctl)" ]; then
systemctl restart dnsmasq
else
service dnsmasq restart
fi
# service already running - reload config
if [ -x "$(command -v systemctl)" ]; then
systemctl restart dnsmasq
else
service dnsmasq restart
fi
else
# service not running, start it up
if [ -x "$(command -v systemctl)" ]; then
systemctl start dnsmasq
else
service dnsmasq start
fi
# service not running, start it up
if [ -x "$(command -v systemctl)" ]; then
systemctl start dnsmasq
else
service dnsmasq start
fi
fi
echo " done!"
}
@ -193,26 +191,24 @@ DisplayBlist() {
verbose=false
echo -e " Displaying Gravity Affected Domains \n"
count=1
while IFS= read -r AD
do
echo "${count}: $AD"
while IFS= read -r AD; do
echo "${count}: ${AD}"
count=$((count+1))
done < "$blacklist"
done < "${blacklist}"
}
###################################################
for var in "$@"
do
case "$var" in
"-nr"| "--noreload" ) reload=false;;
"-d" | "--delmode" ) addmode=false;;
"-f" | "--force" ) force=true;;
"-q" | "--quiet" ) verbose=false;;
"-h" | "--help" ) helpFunc;;
"-l" | "--list" ) DisplayBlist;;
* ) HandleOther "$var";;
esac
for var in "$@"; do
case "$var" in
"-nr"| "--noreload" ) reload=false;;
"-d" | "--delmode" ) addmode=false;;
"-f" | "--force" ) force=true;;
"-q" | "--quiet" ) verbose=false;;
"-h" | "--help" ) helpFunc;;
"-l" | "--list" ) DisplayBlist;;
* ) HandleOther "$var";;
esac
done
PopBlacklistFile
@ -220,7 +216,7 @@ PopBlacklistFile
if ${modifyHost} || ${force}; then
ModifyHostFile
else
if ${verbose}; then
if ${verbose}; then
echo "::: No changes need to be made"
fi
exit 1

View File

@ -19,9 +19,9 @@ today=$(date "+%b %e")
CalcBlockedDomains() {
CheckIPv6
if [ -e "$gravity" ]; then
if [ -e "${gravity}" ]; then
#Are we IPV6 or IPV4?
if [[ -n ${piholeIPv6} ]];then
if [[ -n ${piholeIPv6} ]]; then
#We are IPV6
blockedDomainsTotal=$(wc -l /etc/pihole/gravity.list | awk '{print $1/2}')
else
@ -34,15 +34,15 @@ CalcBlockedDomains() {
}
CalcQueriesToday() {
if [ -e "$piLog" ];then
queriesToday=$(cat "$piLog" | grep "$today" | awk '/query/ {print $6}' | wc -l)
if [ -e "${piLog}" ]; then
queriesToday=$(cat "${piLog}" | grep "${today}" | awk '/query/ {print $6}' | wc -l)
else
queriesToday="Err."
fi
}
CalcblockedToday() {
if [ -e "$piLog" ] && [ -e "$gravity" ];then
if [ -e "${piLog}" ] && [ -e "${gravity}" ];then
blockedToday=$(cat ${piLog} | awk '/\/etc\/pihole\/gravity.list/ && !/address/ {print $6}' | wc -l)
else
blockedToday="Err."
@ -50,11 +50,11 @@ CalcblockedToday() {
}
CalcPercentBlockedToday() {
if [ "$queriesToday" != "Err." ] && [ "$blockedToday" != "Err." ]; then
if [ "$queriesToday" != 0 ]; then #Fixes divide by zero error :)
#scale 2 rounds the number down, so we'll do scale 4 and then trim the last 2 zeros
percentBlockedToday=$(echo "scale=4; $blockedToday/$queriesToday*100" | bc)
percentBlockedToday=$(sed 's/.\{2\}$//' <<< "$percentBlockedToday")
if [ "${queriesToday}" != "Err." ] && [ "${blockedToday}" != "Err." ]; then
if [ "${queriesToday}" != 0 ]; then #Fixes divide by zero error :)
#scale 2 rounds the number down, so we'll do scale 4 and then trim the last 2 zeros
percentBlockedToday=$(echo "scale=4; ${blockedToday}/${queriesToday}*100" | bc)
percentBlockedToday=$(sed 's/.\{2\}$//' <<< "${percentBlockedToday}")
else
percentBlockedToday=0
fi
@ -64,8 +64,8 @@ CalcPercentBlockedToday() {
CheckIPv6() {
piholeIPv6file="/etc/pihole/.useIPv6"
if [[ -f ${piholeIPv6file} ]];then
# If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
# If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
fi
}
@ -80,8 +80,7 @@ outputJSON() {
}
normalChrono() {
for (( ; ; ))
do
for (( ; ; )); do
clear
# Displays a colorful Pi-hole logo
echo " ___ _ _ _"
@ -111,11 +110,11 @@ normalChrono() {
CalcBlockedDomains
echo "Blocking: $blockedDomainsTotal"
echo "Blocking: ${blockedDomainsTotal}"
#below commented line does not add up to todaysQueryCount
#echo "Queries: $todaysQueryCountV4 / $todaysQueryCountV6"
echo "Queries: $queriesToday" #same total calculation as dashboard
echo "Pi-holed: $blockedToday ($percentBlockedToday%)"
echo "Queries: ${queriesToday}" #same total calculation as dashboard
echo "Pi-holed: ${blockedToday} (${percentBlockedToday}%)"
sleep 5
done
@ -139,11 +138,10 @@ if [[ $# = 0 ]]; then
normalChrono
fi
for var in "$@"
do
case "$var" in
"-j" | "--json" ) outputJSON;;
"-h" | "--help" ) displayHelp;;
* ) exit 1;;
esac
for var in "$@"; do
case "$var" in
"-j" | "--json" ) outputJSON;;
"-h" | "--help" ) displayHelp;;
* ) exit 1;;
esac
done

View File

@ -1,4 +1,4 @@
#/usr/bin/env bash
usr/bin/env bash
# Pi-hole: A black hole for Internet advertisements
# (c) 2015, 2016 by Jacob Salmela
# Network-wide ad blocking via your Raspberry Pi
@ -39,7 +39,7 @@ EOM
######## FIRST CHECK ########
# Must be root to debug
if [[ "$EUID" -eq 0 ]]; then
if [[ "${EUID}" -eq 0 ]]; then
echo "::: Script is executing as root user..."
else
echo "::: Non-root user detected..."
@ -54,7 +54,7 @@ else
fi
# Ensure the file exists, create if not, clear if exists.
if [ ! -f "$DEBUG_LOG" ]; then
if [ ! -f "${DEBUG_LOG}" ]; then
${SUDO} touch ${DEBUG_LOG}
${SUDO} chmod 644 ${DEBUG_LOG}
${SUDO} chown "$USER":root ${DEBUG_LOG}
@ -64,25 +64,25 @@ fi
### Private functions exist here ###
log_write() {
echo "$1" >> "${DEBUG_LOG}"
echo "${1}" >> "${DEBUG_LOG}"
}
version_check() {
log_write "############################################################"
log_write "########## Installed Versions ##########"
log_write "############################################################"
log_write "############################################################"
log_write "########## Installed Versions ##########"
log_write "############################################################"
echo "::: Detecting Pi-hole installed versions."
pi_hole_ver="$(cd /etc/.pihole/ && git describe --tags --abbrev=0)" \
&& log_write "Pi-hole Version: $pi_hole_ver" || log_write "Pi-hole git repository not detected."
admin_ver="$(cd /var/www/html/admin && git describe --tags --abbrev=0)" \
&& log_write "WebUI Version: $admin_ver" || log_write "Pi-hole Admin Pages git repository not detected."
echo "::: Detecting Pi-hole installed versions."
pi_hole_ver="$(cd /etc/.pihole/ && git describe --tags --abbrev=0)" \
&& log_write "Pi-hole Version: $pi_hole_ver" || log_write "Pi-hole git repository not detected."
admin_ver="$(cd /var/www/html/admin && git describe --tags --abbrev=0)" \
&& log_write "WebUI Version: $admin_ver" || log_write "Pi-hole Admin Pages git repository not detected."
echo "::: Writing lighttpd version to logfile."
light_ver="$(lighttpd -v |& head -n1)" && log_write "${light_ver}" || log_write "lighttpd not installed."
echo "::: Writing lighttpd version to logfile."
light_ver="$(lighttpd -v |& head -n1)" && log_write "${light_ver}" || log_write "lighttpd not installed."
echo "::: Writing PHP version to logfile."
php_ver="$(php -v |& head -n1)" && log_write "${php_ver}" || log_write "PHP not installed."
echo "::: Writing PHP version to logfile."
php_ver="$(php -v |& head -n1)" && log_write "${php_ver}" || log_write "PHP not installed."
}
distro_check() {
@ -94,7 +94,7 @@ distro_check() {
TMP=$(cat /etc/*release || echo "Failed to find release")
echo "::: Writing OS Distribution release to logfile."
echo "$TMP" >> ${DEBUG_LOG}
echo "${TMP}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
}
@ -103,103 +103,96 @@ ip_check() {
echo "######## IP Address Information #########" >> ${DEBUG_LOG}
echo "############################################################" >> ${DEBUG_LOG}
echo "::: Writing local IPs to logfile"
IPADDR="$(ip a | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "inet") print $(i+1) }')"
echo "$IPADDR" >> ${DEBUG_LOG}
echo "::: Writing local IPs to logfile"
IPADDR="$(ip a | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "inet") print $(i+1) }')"
echo "${IPADDR}" >> ${DEBUG_LOG}
IP6ADDR="$(ip a | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "inet6") print $(i+1) }')" \
&& echo "$IP6ADDR" >> ${DEBUG_LOG} || echo "No IPv6 addresses found." >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
IP6ADDR="$(ip a | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "inet6") print $(i+1) }')" \
&& echo "${IP6ADDR}" >> ${DEBUG_LOG} || echo "No IPv6 addresses found." >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
echo "::: Locating default gateway and checking connectivity"
GATEWAY=$(ip r | grep default | cut -d ' ' -f 3)
if [[ $? = 0 ]]
then
echo "::: Pinging default IPv4 gateway..."
GATEWAY_CHECK=$(ping -q -w 3 -c 3 -n "${GATEWAY}" | tail -n3)
if [[ $? = 0 ]]
then
echo "IPv4 Gateway check:" >> ${DEBUG_LOG}
else
echo "IPv4 Gateway check failed:" >> ${DEBUG_LOG}
fi
echo "$GATEWAY_CHECK" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
echo "::: Locating default gateway and checking connectivity"
GATEWAY=$(ip r | grep default | cut -d ' ' -f 3)
if [[ $? = 0 ]]; then
echo "::: Pinging default IPv4 gateway..."
GATEWAY_CHECK=$(ping -q -w 3 -c 3 -n "${GATEWAY}" | tail -n3)
if [[ $? = 0 ]]; then
echo "IPv4 Gateway check:" >> ${DEBUG_LOG}
else
echo "IPv4 Gateway check failed:" >> ${DEBUG_LOG}
fi
echo "${GATEWAY_CHECK}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
echo "::: Pinging Internet via IPv4..."
INET_CHECK=$(ping -q -w 5 -c 3 -n 8.8.8.8 | tail -n3)
if [[ $? = 0 ]]
then
echo "IPv4 Internet check:" >> ${DEBUG_LOG}
else
echo "IPv4 Internet check failed:" >> ${DEBUG_LOG}
fi
echo "$INET_CHECK" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
fi
echo "::: Pinging Internet via IPv4..."
INET_CHECK=$(ping -q -w 5 -c 3 -n 8.8.8.8 | tail -n3)
if [[ $? = 0 ]]; then
echo "IPv4 Internet check:" >> ${DEBUG_LOG}
else
echo "IPv4 Internet check failed:" >> ${DEBUG_LOG}
fi
echo "${INET_CHECK}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
fi
GATEWAY6=$(ip -6 r | grep default | cut -d ' ' -f 3)
if [[ $? = 0 ]]
then
echo "::: Pinging default IPv6 gateway..."
GATEWAY6_CHECK=$(ping6 -q -w 3 -c 3 -n "${GATEWAY6}" | tail -n3)
if [[ $? = 0 ]]
then
echo "IPv6 Gateway check:" >> ${DEBUG_LOG}
else
echo "IPv6 Gateway check failed:" >> ${DEBUG_LOG}
fi
GATEWAY6=$(ip -6 r | grep default | cut -d ' ' -f 3)
if [[ $? = 0 ]]; then
echo "::: Pinging default IPv6 gateway..."
GATEWAY6_CHECK=$(ping6 -q -w 3 -c 3 -n "${GATEWAY6}" | tail -n3)
if [[ $? = 0 ]]; then
echo "IPv6 Gateway check:" >> ${DEBUG_LOG}
else
echo "IPv6 Gateway check failed:" >> ${DEBUG_LOG}
fi
echo "::: Pinging Internet via IPv6..."
GATEWAY6_CHECK=$(ping6 -q -w 3 -c 3 -n 2001:4860:4860::8888 | tail -n3)
if [[ $? = 0 ]]
then
echo "IPv6 Internet check:" >> ${DEBUG_LOG}
else
echo "IPv6 Internet check failed:" >> ${DEBUG_LOG}
fi
echo "::: Pinging Internet via IPv6..."
GATEWAY6_CHECK=$(ping6 -q -w 3 -c 3 -n 2001:4860:4860::8888 | tail -n3)
if [[ $? = 0 ]]; then
echo "IPv6 Internet check:" >> ${DEBUG_LOG}
else
echo "IPv6 Internet check failed:" >> ${DEBUG_LOG}
fi
else
GATEWAY_CHECK="No IPv6 Gateway Detected"
fi
echo "$GATEWAY_CHECK" >> ${DEBUG_LOG}
else
GATEWAY_CHECK="No IPv6 Gateway Detected"
fi
echo "${GATEWAY_CHECK}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
}
hostnameCheck() {
echo "############################################################" >> ${DEBUG_LOG}
echo "############################################################" >> ${DEBUG_LOG}
echo "######## Hostname Information #########" >> ${DEBUG_LOG}
echo "############################################################" >> ${DEBUG_LOG}
echo "::: Writing locally configured hostnames to logfile"
# Write the hostname output to compare against entries in /etc/hosts, which is logged next
echo "This Pi-hole is: $(hostname)" >> ${DEBUG_LOG}
echo "::: Writing locally configured hostnames to logfile"
# Write the hostname output to compare against entries in /etc/hosts, which is logged next
echo "This Pi-hole is: $(hostname)" >> ${DEBUG_LOG}
echo "::: Writing hosts file to debug log..."
echo "### Hosts ###" >> ${DEBUG_LOG}
echo "::: Writing hosts file to debug log..."
echo "### Hosts ###" >> ${DEBUG_LOG}
if [ -e "$HOSTSFILE" ]
then
cat "$HOSTSFILE" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
else
echo "No hosts file found!" >> ${DEBUG_LOG}
printf ":::\tNo hosts file found!\n"
fi
if [ -e "${HOSTSFILE}" ]; then
cat "${HOSTSFILE}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
else
echo "No hosts file found!" >> ${DEBUG_LOG}
printf ":::\tNo hosts file found!\n"
fi
}
portCheck() {
echo "############################################################" >> ${DEBUG_LOG}
echo "############################################################" >> ${DEBUG_LOG}
echo "######## Open Port Information #########" >> ${DEBUG_LOG}
echo "############################################################" >> ${DEBUG_LOG}
echo "::: Detecting local server port 80 and 53 processes."
echo "::: Detecting local server port 80 and 53 processes."
${SUDO} lsof -i :80 >> ${DEBUG_LOG}
${SUDO} lsof -i :53 >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
${SUDO} lsof -i :80 >> ${DEBUG_LOG}
${SUDO} lsof -i :53 >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
}
testResolver() {
@ -209,59 +202,57 @@ testResolver() {
# Find a blocked url that has not been whitelisted.
TESTURL="doubleclick.com"
if [ -s "$WHITELISTMATCHES" ]; then
TESTURL="doubleclick.com"
if [ -s "${WHITELISTMATCHES}" ]; then
while read -r line; do
CUTURL=${line#*" "}
if [ "$CUTURL" != "Pi-Hole.IsWorking.OK" ]; then
if [ "${CUTURL}" != "Pi-Hole.IsWorking.OK" ]; then
while read -r line2; do
CUTURL2=${line2#*" "}
if [ "$CUTURL" != "$CUTURL2" ]; then
TESTURL="$CUTURL"
if [ "${CUTURL}" != "${CUTURL2}" ]; then
TESTURL="${CUTURL}"
break 2
fi
done < "$WHITELISTMATCHES"
done < "${WHITELISTMATCHES}"
fi
done < "$GRAVITYFILE"
done < "${GRAVITYFILE}"
fi
echo "Resolution of $TESTURL from Pi-hole:" >> ${DEBUG_LOG}
LOCALDIG=$(dig "$TESTURL" @127.0.0.1)
if [[ $? = 0 ]]
then
echo "$LOCALDIG" >> ${DEBUG_LOG}
echo "Resolution of ${TESTURL} from Pi-hole:" >> ${DEBUG_LOG}
LOCALDIG=$(dig "${TESTURL}" @127.0.0.1)
if [[ $? = 0 ]]; then
echo "${LOCALDIG}" >> ${DEBUG_LOG}
else
echo "Failed to resolve $TESTURL on Pi-hole" >> ${DEBUG_LOG}
echo "Failed to resolve ${TESTURL} on Pi-hole" >> ${DEBUG_LOG}
fi
echo >> ${DEBUG_LOG}
echo "Resolution of $TESTURL from 8.8.8.8:" >> ${DEBUG_LOG}
REMOTEDIG=$(dig "$TESTURL" @8.8.8.8)
if [[ $? = 0 ]]
then
echo "$REMOTEDIG" >> ${DEBUG_LOG}
echo "Resolution of ${TESTURL} from 8.8.8.8:" >> ${DEBUG_LOG}
REMOTEDIG=$(dig "${TESTURL}" @8.8.8.8)
if [[ $? = 0 ]]; then
echo "${REMOTEDIG}" >> ${DEBUG_LOG}
else
echo "Failed to resolve $TESTURL on 8.8.8.8" >> ${DEBUG_LOG}
echo "Failed to resolve ${TESTURL} on 8.8.8.8" >> ${DEBUG_LOG}
fi
echo >> ${DEBUG_LOG}
echo "Pi-hole dnsmasq specific records lookups" >> ${DEBUG_LOG}
echo "Cache Size:" >> ${DEBUG_LOG}
dig +short chaos txt cachesize.bind >> ${DEBUG_LOG}
echo "Insertions count:" >> ${DEBUG_LOG}
dig +short chaos txt insertions.bind >> ${DEBUG_LOG}
echo "Evictions count:" >> ${DEBUG_LOG}
dig +short chaos txt evictions.bind >> ${DEBUG_LOG}
echo "Misses count:" >> ${DEBUG_LOG}
dig +short chaos txt misses.bind >> ${DEBUG_LOG}
echo "Hits count:" >> ${DEBUG_LOG}
dig +short chaos txt hits.bind >> ${DEBUG_LOG}
echo "Auth count:" >> ${DEBUG_LOG}
dig +short chaos txt auth.bind >> ${DEBUG_LOG}
echo "Upstream Servers:" >> ${DEBUG_LOG}
dig +short chaos txt servers.bind >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
echo "Cache Size:" >> ${DEBUG_LOG}
dig +short chaos txt cachesize.bind >> ${DEBUG_LOG}
echo "Insertions count:" >> ${DEBUG_LOG}
dig +short chaos txt insertions.bind >> ${DEBUG_LOG}
echo "Evictions count:" >> ${DEBUG_LOG}
dig +short chaos txt evictions.bind >> ${DEBUG_LOG}
echo "Misses count:" >> ${DEBUG_LOG}
dig +short chaos txt misses.bind >> ${DEBUG_LOG}
echo "Hits count:" >> ${DEBUG_LOG}
dig +short chaos txt hits.bind >> ${DEBUG_LOG}
echo "Auth count:" >> ${DEBUG_LOG}
dig +short chaos txt auth.bind >> ${DEBUG_LOG}
echo "Upstream Servers:" >> ${DEBUG_LOG}
dig +short chaos txt servers.bind >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
}
checkProcesses() {
@ -271,12 +262,11 @@ checkProcesses() {
echo ":::"
echo "::: Logging status of lighttpd and dnsmasq..."
PROCESSES=( lighttpd dnsmasq )
for i in "${PROCESSES[@]}"
do
for i in "${PROCESSES[@]}"; do
echo "" >> ${DEBUG_LOG}
echo -n "$i" >> "$DEBUG_LOG"
echo -n "${i}" >> "${DEBUG_LOG}"
echo " processes status:" >> ${DEBUG_LOG}
${SUDO} systemctl -l status "$i" >> "$DEBUG_LOG"
${SUDO} systemctl -l status "${i}" >> "${DEBUG_LOG}"
done
echo >> ${DEBUG_LOG}
}
@ -286,26 +276,24 @@ debugLighttpd() {
echo "#######################################" >> ${DEBUG_LOG}
echo "############ lighttpd.conf ############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$LIGHTTPDFILE" ]
then
if [ -e "${LIGHTTPDFILE}" ]; then
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> ${DEBUG_LOG}
if [ ! -z "${line}" ]; then
[[ "${line}" =~ ^#.*$ ]] && continue
echo "${line}" >> ${DEBUG_LOG}
fi
done < "$LIGHTTPDFILE"
done < "${LIGHTTPDFILE}"
echo >> ${DEBUG_LOG}
else
echo "No lighttpd.conf file found!" >> ${DEBUG_LOG}
printf ":::\tNo lighttpd.conf file found\n"
fi
if [ -e "$LIGHTTPDERRFILE" ]
then
if [ -e "${LIGHTTPDERRFILE}" ]; then
echo "#######################################" >> ${DEBUG_LOG}
echo "######### lighttpd error.log ##########" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
cat "$LIGHTTPDERRFILE" >> ${DEBUG_LOG}
cat "${LIGHTTPDERRFILE}" >> ${DEBUG_LOG}
else
echo "No lighttpd error.log file found!" >> ${DEBUG_LOG}
printf ":::\tNo lighttpd error.log file found\n"
@ -328,15 +316,14 @@ echo "::: Writing dnsmasq.conf to debug log..."
echo "#######################################" >> ${DEBUG_LOG}
echo "############### Dnsmasq ###############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$DNSMASQFILE" ]
then
if [ -e "${DNSMASQFILE}" ]; then
#cat $DNSMASQFILE >> $DEBUG_LOG
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> ${DEBUG_LOG}
fi
done < "$DNSMASQFILE"
if [ ! -z "${line}" ]; then
[[ "${line}" =~ ^#.*$ ]] && continue
echo "${line}" >> ${DEBUG_LOG}
fi
done < "${DNSMASQFILE}"
echo >> ${DEBUG_LOG}
else
echo "No dnsmasq.conf file found!" >> ${DEBUG_LOG}
@ -347,14 +334,13 @@ echo "::: Writing 01-pihole.conf to debug log..."
echo "#######################################" >> ${DEBUG_LOG}
echo "########### 01-pihole.conf ############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$PIHOLECONFFILE" ]
then
if [ -e "${PIHOLECONFFILE}" ]; then
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> ${DEBUG_LOG}
fi
done < "$PIHOLECONFFILE"
if [ ! -z "${line}" ]; then
[[ "${line}" =~ ^#.*$ ]] && continue
echo "${line}" >> ${DEBUG_LOG}
fi
done < "${PIHOLECONFFILE}"
echo >> ${DEBUG_LOG}
else
echo "No 01-pihole.conf file found!" >> ${DEBUG_LOG}
@ -365,9 +351,8 @@ echo "::: Writing size of gravity.list to debug log..."
echo "#######################################" >> ${DEBUG_LOG}
echo "############ gravity.list #############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$GRAVITYFILE" ]
then
wc -l "$GRAVITYFILE" >> ${DEBUG_LOG}
if [ -e "${GRAVITYFILE}" ]; then
wc -l "${GRAVITYFILE}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
else
echo "No gravity.list file found!" >> ${DEBUG_LOG}
@ -380,9 +365,8 @@ echo "::: Writing whitelist to debug log..."
echo "#######################################" >> ${DEBUG_LOG}
echo "############## Whitelist ##############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$WHITELISTFILE" ]
then
cat "$WHITELISTFILE" >> ${DEBUG_LOG}
if [ -e "${WHITELISTFILE}" ]; then
cat "${WHITELISTFILE}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
else
echo "No whitelist.txt file found!" >> ${DEBUG_LOG}
@ -393,9 +377,8 @@ echo "::: Writing blacklist to debug log..."
echo "#######################################" >> ${DEBUG_LOG}
echo "############## Blacklist ##############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$BLACKLISTFILE" ]
then
cat "$BLACKLISTFILE" >> ${DEBUG_LOG}
if [ -e "${BLACKLISTFILE}" ]; then
cat "${BLACKLISTFILE}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
else
echo "No blacklist.txt file found!" >> ${DEBUG_LOG}
@ -406,14 +389,13 @@ echo "::: Writing adlists.list to debug log..."
echo "#######################################" >> ${DEBUG_LOG}
echo "############ adlists.list #############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$ADLISTSFILE" ]
then
while read -r line; do
if [ ! -z "$line" ]; then
[[ "$line" =~ ^#.*$ ]] && continue
echo "$line" >> ${DEBUG_LOG}
fi
done < "$ADLISTSFILE"
if [ -e "${ADLISTSFILE}" ]; then
while read -r line; do
if [ ! -z "${line}" ]; then
[[ "${line}" =~ ^#.*$ ]] && continue
echo "${line}" >> ${DEBUG_LOG}
fi
done < "${ADLISTSFILE}"
echo >> ${DEBUG_LOG}
else
echo "No adlists.list file found... using adlists.default!" >> ${DEBUG_LOG}
@ -428,10 +410,9 @@ dumpPiHoleLog() {
echo "#######################################" >> ${DEBUG_LOG}
echo "############# pihole.log ##############" >> ${DEBUG_LOG}
echo "#######################################" >> ${DEBUG_LOG}
if [ -e "$PIHOLELOG" ]
then
if [ -e "${PIHOLELOG}" ]; then
while true; do
tail -f "$PIHOLELOG" >> ${DEBUG_LOG}
tail -f "${PIHOLELOG}" >> ${DEBUG_LOG}
echo >> ${DEBUG_LOG}
done
else
@ -442,25 +423,24 @@ dumpPiHoleLog() {
# Anything to be done after capturing of pihole.log terminates
finalWork() {
echo "::: Finshed debugging!"
echo "::: The debug log can be uploaded to Termbin.com for easier sharing."
read -r -p "::: Would you like to upload the log? [y/N] " response
case ${response} in
[yY][eE][sS]|[yY])
TERMBIN=$(cat /var/log/pihole_debug.log | nc termbin.com 9999)
;;
*)
echo "::: Log will NOT be uploaded to Termbin."
;;
esac
echo "::: Finshed debugging!"
echo "::: The debug log can be uploaded to Termbin.com for easier sharing."
read -r -p "::: Would you like to upload the log? [y/N] " response
case ${response} in
[yY][eE][sS]|[yY])
TERMBIN=$(cat /var/log/pihole_debug.log | nc termbin.com 9999)
;;
*)
echo "::: Log will NOT be uploaded to Termbin."
;;
esac
# Check if termbin.com is reachable. When it's not, point to local log instead
if [ -n "$TERMBIN" ]
then
echo "::: Debug log can be found at : $TERMBIN"
else
echo "::: Debug log can be found at : /var/log/pihole_debug.log"
fi
# Check if termbin.com is reachable. When it's not, point to local log instead
if [ -n "${TERMBIN}" ]; then
echo "::: Debug log can be found at : ${TERMBIN}"
else
echo "::: Debug log can be found at : /var/log/pihole_debug.log"
fi
}
trap finalWork EXIT

View File

@ -15,28 +15,28 @@
# Borrowed from adafruit-pitft-helper < borrowed from raspi-config
# https://github.com/adafruit/Adafruit-PiTFT-Helper/blob/master/adafruit-pitft-helper#L324-L334
getInitSys() {
if command -v systemctl > /dev/null && systemctl | grep -q '\-\.mount'; then
SYSTEMD=1
elif [ -f /etc/init.d/cron ] && [ ! -h /etc/init.d/cron ]; then
SYSTEMD=0
else
echo "Unrecognised init system"
return 1
fi
if command -v systemctl > /dev/null && systemctl | grep -q '\-\.mount'; then
SYSTEMD=1
elif [ -f /etc/init.d/cron ] && [ ! -h /etc/init.d/cron ]; then
SYSTEMD=0
else
echo "Unrecognised init system"
return 1
fi
}
# Borrowed from adafruit-pitft-helper:
# https://github.com/adafruit/Adafruit-PiTFT-Helper/blob/master/adafruit-pitft-helper#L274-L285
autoLoginPiToConsole() {
if [ -e /etc/init.d/lightdm ]; then
if [ ${SYSTEMD} -eq 1 ]; then
systemctl set-default multi-user.target
ln -fs /etc/systemd/system/autologin@.service /etc/systemd/system/getty.target.wants/getty@tty1.service
else
update-rc.d lightdm disable 2
sed /etc/inittab -i -e "s/1:2345:respawn:\/sbin\/getty --noclear 38400 tty1/1:2345:respawn:\/bin\/login -f pi tty1 <\/dev\/tty1 >\/dev\/tty1 2>&1/"
fi
fi
if [ -e /etc/init.d/lightdm ]; then
if [ ${SYSTEMD} -eq 1 ]; then
systemctl set-default multi-user.target
ln -fs /etc/systemd/system/autologin@.service /etc/systemd/system/getty.target.wants/getty@tty1.service
else
update-rc.d lightdm disable 2
sed /etc/inittab -i -e "s/1:2345:respawn:\/sbin\/getty --noclear 38400 tty1/1:2345:respawn:\/bin\/login -f pi tty1 <\/dev\/tty1 >\/dev\/tty1 2>&1/"
fi
fi
}
######### SCRIPT ###########

View File

@ -18,17 +18,17 @@ piholeGitUrl="https://github.com/pi-hole/pi-hole.git"
piholeFilesDir="/etc/.pihole"
spinner() {
local pid=$1
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "$pid")" ]; do
local pid=${1}
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "${pid}")" ]; do
local temp=${spinstr#?}
printf " [%c] " "$spinstr"
local spinstr=${temp}${spinstr%"$temp"}
sleep ${delay}
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
printf " [%c] " "${spinstr}"
local spinstr=${temp}${spinstr%"$temp"}
sleep ${delay}
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
}
getGitFiles() {
@ -37,45 +37,45 @@ getGitFiles() {
echo ":::"
echo "::: Checking for existing repository..."
if is_repo "${1}"; then
update_repo "${1}"
update_repo "${1}"
else
make_repo "${1}" "${2}"
fi
make_repo "${1}" "${2}"
fi
}
is_repo() {
# Use git to check if directory is currently under VCS
# Use git to check if directory is currently under VCS
echo -n "::: Checking $1 is a repo..."
cd "${1}" &> /dev/null || return 1
git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1
}
make_repo() {
# Remove the non-repod interface and clone the interface
echo -n "::: Cloning $2 into $1..."
rm -rf "${1}"
git clone -q --depth 1 "${2}" "${1}" > /dev/null & spinner $!
echo " done!"
# Remove the non-repod interface and clone the interface
echo -n "::: Cloning $2 into $1..."
rm -rf "${1}"
git clone -q --depth 1 "${2}" "${1}" > /dev/null & spinner $!
echo " done!"
}
update_repo() {
# Pull the latest commits
echo -n "::: Updating repo in $1..."
cd "${1}" || exit 1
git stash -q > /dev/null & spinner $!
git pull -q > /dev/null & spinner $!
echo " done!"
# Pull the latest commits
echo -n "::: Updating repo in $1..."
cd "${1}" || exit 1
git stash -q > /dev/null & spinner $!
git pull -q > /dev/null & spinner $!
echo " done!"
}
if [ ! -d "/etc/.pihole" ]; then #This is unlikely
echo "::: Critical Error: Pi-Hole repo missing from system!"
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole"
exit 1;
echo "::: Critical Error: Pi-Hole repo missing from system!"
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole"
exit 1;
fi
if [ ! -d "/var/www/html/admin" ]; then #This is unlikely
echo "::: Critical Error: Pi-Hole repo missing from system!"
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole"
exit 1;
echo "::: Critical Error: Pi-Hole repo missing from system!"
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole"
exit 1;
fi
echo "::: Checking for updates..."
@ -105,40 +105,38 @@ echo ":::"
if [[ ${piholeVersion} == ${piholeVersionLatest} && ${webVersion} == ${webVersionLatest} ]]; then
echo "::: Everything is up to date!"
echo ""
exit 0
echo "::: Everything is up to date!"
echo ""
exit 0
elif [[ ${piholeVersion} == ${piholeVersionLatest} && ${webVersion} != ${webVersionLatest} ]]; then
echo "::: Pi-hole Web Admin files out of date"
getGitFiles ${webInterfaceDir} ${webInterfaceGitUrl}
echo ":::"
webVersion=$(pihole -v -a -c)
echo "::: Web Admin version is now at ${webVersion}"
echo "::: If you had made any changes in '/var/www/html/admin', they have been stashed using 'git stash'"
echo ""
echo "::: Pi-hole Web Admin files out of date"
getGitFiles ${webInterfaceDir} ${webInterfaceGitUrl}
echo ":::"
webVersion=$(pihole -v -a -c)
echo "::: Web Admin version is now at ${webVersion}"
echo "::: If you had made any changes in '/var/www/html/admin', they have been stashed using 'git stash'"
echo ""
elif [[ ${piholeVersion} != ${piholeVersionLatest} && ${webVersion} == ${webVersionLatest} ]]; then
echo "::: Pi-hole core files out of date"
getGitFiles ${piholeFilesDir} ${piholeGitUrl}
/etc/.pihole/automated\ install/basic-install.sh --reconfigure --unattended
echo ":::"
piholeVersion=$(pihole -v -p -c)
echo "::: Pi-hole version is now at ${piholeVersion}"
echo "::: If you had made any changes in '/etc/.pihole', they have been stashed using 'git stash'"
echo ""
echo "::: Pi-hole core files out of date"
getGitFiles ${piholeFilesDir} ${piholeGitUrl}
/etc/.pihole/automated\ install/basic-install.sh --reconfigure --unattended
echo ":::"
piholeVersion=$(pihole -v -p -c)
echo "::: Pi-hole version is now at ${piholeVersion}"
echo "::: If you had made any changes in '/etc/.pihole', they have been stashed using 'git stash'"
echo ""
elif [[ ${piholeVersion} != ${piholeVersionLatest} && ${webVersion} != ${webVersionLatest} ]]; then
echo "::: Updating Everything"
getGitFiles ${piholeFilesDir} ${piholeGitUrl}
/etc/.pihole/automated\ install/basic-install.sh --unattended
webVersion=$(pihole -v -a -c)
piholeVersion=$(pihole -v -p -c)
echo ":::"
echo "::: Pi-hole version is now at ${piholeVersion}"
echo "::: If you had made any changes in '/etc/.pihole', they have been stashed using 'git stash'"
echo ":::"
echo "::: Pi-hole version is now at ${piholeVersion}"
echo "::: If you had made any changes in '/etc/.pihole', they have been stashed using 'git stash'"
echo ""
echo "::: Updating Everything"
getGitFiles ${piholeFilesDir} ${piholeGitUrl}
/etc/.pihole/automated\ install/basic-install.sh --unattended
webVersion=$(pihole -v -a -c)
piholeVersion=$(pihole -v -p -c)
echo ":::"
echo "::: Pi-hole version is now at ${piholeVersion}"
echo "::: If you had made any changes in '/etc/.pihole', they have been stashed using 'git stash'"
echo ":::"
echo "::: Pi-hole version is now at ${piholeVersion}"
echo "::: If you had made any changes in '/etc/.pihole', they have been stashed using 'git stash'"
echo ""
fi

View File

@ -15,60 +15,58 @@ latest=false
current=false
normalOutput() {
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo "::: Pi-hole version is $piholeVersion (Latest version is $piholeVersionLatest)"
echo "::: Web-Admin version is $webVersion (Latest version is $webVersionLatest)"
echo "::: Pi-hole version is ${piholeVersion} (Latest version is ${piholeVersionLatest})"
echo "::: Web-Admin version is ${webVersion} (Latest version is ${webVersionLatest})"
}
webOutput() {
for var in "$@"
do
case "$var" in
"-l" | "--latest" ) latest=true;;
"-c" | "--current" ) current=true;;
* ) echo "::: Invalid Option!"; exit 1;
esac
done
for var in "$@"; do
case "${var}" in
"-l" | "--latest" ) latest=true;;
"-c" | "--current" ) current=true;;
* ) echo "::: Invalid Option!"; exit 1;
esac
done
if [[ "${latest}" == true && "${current}" == false ]]; then
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo ${webVersionLatest}
elif [[ "${latest}" == false && "${current}" == true ]]; then
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
echo ${webVersion}
else
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo "::: Web-Admin version is $webVersion (Latest version is $webVersionLatest)"
fi
if [[ "${latest}" == true && "${current}" == false ]]; then
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo ${webVersionLatest}
elif [[ "${latest}" == false && "${current}" == true ]]; then
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
echo ${webVersion}
else
webVersion=$(cd /var/www/html/admin/ && git describe --tags --abbrev=0)
webVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo "::: Web-Admin version is $webVersion (Latest version is $webVersionLatest)"
fi
}
coreOutput() {
for var in "$@"
do
case "$var" in
"-l" | "--latest" ) latest=true;;
"-c" | "--current" ) current=true;;
* ) echo "::: Invalid Option!"; exit 1;
esac
done
for var in "$@"; do
case "${var}" in
"-l" | "--latest" ) latest=true;;
"-c" | "--current" ) current=true;;
* ) echo "::: Invalid Option!"; exit 1;
esac
done
if [[ "${latest}" == true && "${current}" == false ]]; then
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo ${piholeVersionLatest}
elif [[ "${latest}" == false && "${current}" == true ]]; then
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
echo ${piholeVersion}
else
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo "::: Pi-hole version is $piholeVersion (Latest version is $piholeVersionLatest)"
fi
if [[ "${latest}" == true && "${current}" == false ]]; then
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo ${piholeVersionLatest}
elif [[ "${latest}" == false && "${current}" == true ]]; then
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
echo ${piholeVersion}
else
piholeVersion=$(cd /etc/.pihole/ && git describe --tags --abbrev=0)
piholeVersionLatest=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/releases/latest | grep -Po '"tag_name":.*?[^\\]",' | perl -pe 's/"tag_name": "//; s/^"//; s/",$//')
echo "::: Pi-hole version is $piholeVersion (Latest version is $piholeVersionLatest)"
fi
}
helpFunc() {
@ -93,11 +91,10 @@ if [[ $# = 0 ]]; then
normalOutput
fi
for var in "$@"
do
case "$var" in
"-a" | "--admin" ) shift; webOutput "$@";;
"-p" | "--pihole" ) shift; coreOutput "$@" ;;
"-h" | "--help" ) helpFunc;;
esac
for var in "$@"; do
case "${var}" in
"-a" | "--admin" ) shift; webOutput "$@";;
"-p" | "--pihole" ) shift; coreOutput "$@" ;;
"-h" | "--help" ) helpFunc;;
esac
done

View File

@ -48,160 +48,158 @@ domToRemoveList=()
piholeIPfile=/etc/pihole/piholeIP
piholeIPv6file=/etc/pihole/.useIPv6
if [[ -f ${piholeIPfile} ]];then
# If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIP=$(cat ${piholeIPfile})
#rm $piholeIPfile
if [[ -f ${piholeIPfile} ]]; then
# If the file exists, it means it was exported from the installation script and we should use that value instead of detecting it in this script
piholeIP=$(cat ${piholeIPfile})
#rm $piholeIPfile
else
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev "$IPv4dev" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*}
# Otherwise, the IP address can be taken directly from the machine, which will happen when the script is run by the user and not the installation script
IPv4dev=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++)if($i~/dev/)print $(i+1)}')
piholeIPCIDR=$(ip -o -f inet addr show dev "${IPv4dev}" | awk '{print $4}' | awk 'END {print}')
piholeIP=${piholeIPCIDR%/*}
fi
modifyHost=false
# After setting defaults, check if there's local overrides
if [[ -r ${piholeDir}/pihole.conf ]];then
echo "::: Local calibration requested..."
. ${piholeDir}/pihole.conf
if [[ -r ${piholeDir}/pihole.conf ]]; then
echo "::: Local calibration requested..."
. ${piholeDir}/pihole.conf
fi
if [[ -f ${piholeIPv6file} ]];then
# If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
if [[ -f ${piholeIPv6file} ]]; then
# If the file exists, then the user previously chose to use IPv6 in the automated installer
piholeIPv6=$(ip -6 route get 2001:4860:4860::8888 | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }')
fi
HandleOther() {
#check validity of domain
#check validity of domain
validDomain=$(echo "$1" | perl -ne'print if /\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/')
if [ -z "$validDomain" ]; then
if [ -z "${validDomain}" ]; then
echo "::: $1 is not a valid argument or domain name"
else
domList=("${domList[@]}" ${validDomain})
domList=("${domList[@]}" ${validDomain})
fi
}
PopWhitelistFile() {
#check whitelist file exists, and if not, create it
if [[ ! -f ${whitelist} ]];then
touch ${whitelist}
if [[ ! -f ${whitelist} ]]; then
touch ${whitelist}
fi
for dom in "${domList[@]}"
do
if ${addmode}; then
AddDomain "$dom"
else
RemoveDomain "$dom"
fi
for dom in "${domList[@]}"; do
if ${addmode}; then
AddDomain "${dom}"
else
RemoveDomain "${dom}"
fi
done
}
AddDomain() {
#| sed 's/\./\\./g'
#| sed 's/\./\\./g'
bool=false
grep -Ex -q "$1" ${whitelist} || bool=true
if ${bool}; then
#domain not found in the whitelist file, add it!
if ${verbose}; then
echo -n "::: Adding $1 to $whitelist..."
fi
echo "$1" >> ${whitelist}
modifyHost=true
#domain not found in the whitelist file, add it!
if ${verbose}; then
echo " done!"
fi
echo -n "::: Adding ${1}to ${whitelist}..."
fi
echo "${1}" >> ${whitelist}
modifyHost=true
if ${verbose}; then
echo " done!"
fi
else
if ${verbose}; then
echo "::: $1 already exists in $whitelist, no need to add!"
echo "::: ${1} already exists in ${whitelist}, no need to add!"
fi
fi
}
RemoveDomain() {
bool=false
grep -Ex -q "$1" ${whitelist} || bool=true
if ${bool}; then
#Domain is not in the whitelist file, no need to Remove
if ${verbose}; then
echo "::: $1 is NOT whitelisted! No need to remove"
fi
else
#Domain is in the whitelist file, add to a temporary array and remove from whitelist file
#if $verbose; then
#echo "::: Un-whitelisting $dom..."
#fi
domToRemoveList=("${domToRemoveList[@]}" $1)
modifyHost=true
fi
bool=false
grep -Ex -q "$1" ${whitelist} || bool=true
if ${bool}; then
#Domain is not in the whitelist file, no need to Remove
if ${verbose}; then
echo "::: ${1} is NOT whitelisted! No need to remove"
fi
else
#Domain is in the whitelist file, add to a temporary array and remove from whitelist file
#if $verbose; then
#echo "::: Un-whitelisting $dom..."
#fi
domToRemoveList=("${domToRemoveList[@]}" ${1})
modifyHost=true
fi
}
ModifyHostFile() {
if ${addmode}; then
#remove domains in from hosts file
if [[ -r ${whitelist} ]];then
# Remove whitelist entries
numberOf=$(cat ${whitelist} | sed '/^\s*$/d' | wc -l)
plural=; [[ "$numberOf" != "1" ]] && plural=s
echo ":::"
echo -n "::: Modifying HOSTS file to whitelist $numberOf domain${plural}..."
awk -F':' '{print $1}' ${whitelist} | while read -r line; do echo "$piholeIP $line"; done > /etc/pihole/whitelist.tmp
awk -F':' '{print $1}' ${whitelist} | while read -r line; do echo "$piholeIPv6 $line"; done >> /etc/pihole/whitelist.tmp
echo "l" >> /etc/pihole/whitelist.tmp
grep -F -x -v -f ${piholeDir}/whitelist.tmp ${adList} > ${piholeDir}/gravity.tmp
rm ${adList}
mv ${piholeDir}/gravity.tmp ${adList}
rm ${piholeDir}/whitelist.tmp
echo " done!"
if ${addmode}; then
#remove domains in from hosts file
if [[ -r ${whitelist} ]]; then
# Remove whitelist entries
numberOf=$(cat ${whitelist} | sed '/^\s*$/d' | wc -l)
plural=; [[ "${numberOf}" != "1" ]] && plural=s
echo ":::"
echo -n "::: Modifying HOSTS file to whitelist $numberOf domain${plural}..."
awk -F':' '{print $1}' ${whitelist} | while read -r line; do echo "${piholeIP} ${line}"; done > /etc/pihole/whitelist.tmp
awk -F':' '{print $1}' ${whitelist} | while read -r line; do echo "${piholeIPv6} ${line}"; done >> /etc/pihole/whitelist.tmp
echo "l" >> /etc/pihole/whitelist.tmp
grep -F -x -v -f ${piholeDir}/whitelist.tmp ${adList} > ${piholeDir}/gravity.tmp
rm ${adList}
mv ${piholeDir}/gravity.tmp ${adList}
rm ${piholeDir}/whitelist.tmp
echo " done!"
fi
else
#we need to add the removed domains to the hosts file
echo ":::"
echo "::: Modifying HOSTS file to un-whitelist domains..."
for rdom in "${domToRemoveList[@]}"
do
if grep -q "$rdom" /etc/pihole/*.domains; then
echo "::: AdLists contain $rdom, re-adding block"
if [[ -n ${piholeIPv6} ]];then
echo -n "::: Restoring block for $rdom on IPv4 and IPv6..."
echo "$rdom" | awk -v ipv4addr="$piholeIP" -v ipv6addr="$piholeIPv6" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> ${adList}
echo " done!"
else
echo -n "::: Restoring block for $rdom on IPv4..."
echo "$rdom" | awk -v ipv4addr="$piholeIP" '{sub(/\r$/,""); print ipv4addr" "$0}' >>${adList}
echo " done!"
fi
fi
echo -n "::: Removing $rdom from $whitelist..."
echo "$rdom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' ${whitelist}
echo " done!"
done
fi
fi
else
#we need to add the removed domains to the hosts file
echo ":::"
echo "::: Modifying HOSTS file to un-whitelist domains..."
for rdom in "${domToRemoveList[@]}"; do
if grep -q "${rdom}" /etc/pihole/*.domains; then
echo "::: AdLists contain ${rdom}, re-adding block"
if [[ -n ${piholeIPv6} ]]; then
echo -n "::: Restoring block for ${rdom} on IPv4 and IPv6..."
echo "${rdom}" | awk -v ipv4addr="${piholeIP}" -v ipv6addr="${piholeIPv6}" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> ${adList}
echo " done!"
else
echo -n "::: Restoring block for ${rdom} on IPv4..."
echo "${rdom}" | awk -v ipv4addr="${piholeIP}" '{sub(/\r$/,""); print ipv4addr" "$0}' >>${adList}
echo " done!"
fi
fi
echo -n "::: Removing $rdom from $whitelist..."
echo "$rdom" | sed 's/\./\\./g' | xargs -I {} perl -i -ne'print unless /'{}'(?!.)/;' ${whitelist}
echo " done!"
done
fi
}
Reload() {
# Reload hosts file
echo ":::"
echo -n "::: Refresh lists in dnsmasq..."
dnsmasqPid=$(pidof dnsmasq)
dnsmasqPid=$(pidof dnsmasq)
if [[ ${dnsmasqPid} ]]; then
# service already running - reload config
if [ -x "$(command -v systemctl)" ]; then
systemctl restart dnsmasq
else
service dnsmasq restart
fi
# service already running - reload config
if [ -x "$(command -v systemctl)" ]; then
systemctl restart dnsmasq
else
service dnsmasq restart
fi
else
# service not running, start it up
if [ -x "$(command -v systemctl)" ]; then
systemctl start dnsmasq
else
service dnsmasq start
fi
# service not running, start it up
if [ -x "$(command -v systemctl)" ]; then
systemctl start dnsmasq
else
service dnsmasq start
fi
fi
echo " done!"
}
@ -210,35 +208,33 @@ DisplayWlist() {
verbose=false
echo -e " Displaying Gravity Resistant Domains \n"
count=1
while IFS= read -r RD
do
echo "${count}: $RD"
while IFS= read -r RD; do
echo "${count}: ${RD}"
count=$((count+1))
done < "$whitelist"
done < "${whitelist}"
}
###################################################
for var in "$@"
do
case "$var" in
"-nr"| "--noreload" ) reload=false;;
"-d" | "--delmode" ) addmode=false;;
"-f" | "--force" ) force=true;;
"-q" | "--quiet" ) verbose=false;;
"-h" | "--help" ) helpFunc;;
"-l" | "--list" ) DisplayWlist;;
* ) HandleOther "$var";;
esac
for var in "$@"; do
case "${var}" in
"-nr"| "--noreload" ) reload=false;;
"-d" | "--delmode" ) addmode=false;;
"-f" | "--force" ) force=true;;
"-q" | "--quiet" ) verbose=false;;
"-h" | "--help" ) helpFunc;;
"-l" | "--list" ) DisplayWlist;;
* ) HandleOther "${var}";;
esac
done
PopWhitelistFile
if ${modifyHost} || ${force}; then
ModifyHostFile
ModifyHostFile
else
if ${verbose}; then
echo ":::"
if ${verbose}; then
echo ":::"
echo "::: No changes need to be made"
fi
exit 1

View File

@ -1,12 +1,11 @@
_pihole()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="blacklist chronometer debug flush help query reconfigure setupLCD uninstall updateGravity updatePihole version whitelist"
_pihole() {
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="blacklist chronometer debug flush help query reconfigure setupLCD uninstall updateGravity updatePihole version whitelist"
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _pihole pihole
complete -F _pihole pihole

View File

@ -48,18 +48,19 @@ runUnattended=false
######## FIRST CHECK ########
# Must be root to install
echo ":::"
if [[ $EUID -eq 0 ]];then
if [[ ${EUID} -eq 0 ]]; then
echo "::: You are root."
else
echo "::: Script called with non-root privileges. The Pi-hole installs server packages and configures"
echo "::: system networking, it requires elevated rights. Please check the contents of the script for"
echo "::: any concerns with this requirement. Please be sure to download this script from a trusted source."
echo ":::"
echo "::: Detecting the presence of the sudo utility for continuation of this install..."
if [ -x "$(command -v sudo)" ];then
echo "::: Script called with non-root privileges. The Pi-hole installs server packages and configures"
echo "::: system networking, it requires elevated rights. Please check the contents of the script for"
echo "::: any concerns with this requirement. Please be sure to download this script from a trusted source."
echo ":::"
echo "::: Detecting the presence of the sudo utility for continuation of this install..."
if [ -x "$(command -v sudo)" ]; then
echo "::: Utility sudo located."
exec curl -sSL https://install.pi-hole.net | sudo bash "$@"
exit $?
exec curl -sSL https://install.pi-hole.net | sudo bash "$@"
exit $?
else
echo "::: sudo is needed for the Web interface to run pihole commands. Please run this script as root and it will be automatically installed."
exit 1
@ -68,7 +69,7 @@ fi
# Compatibility
if [ -x "$(command -v apt-get)" ];then
if [ -x "$(command -v apt-get)" ]; then
#Debian Family
#Decide if php should be `php5` or just `php` (Fixes issues with Ubuntu 16.04 LTS)
phpVer="php5"
@ -76,11 +77,11 @@ if [ -x "$(command -v apt-get)" ];then
#############################################
PKG_MANAGER="apt-get"
PKG_CACHE="/var/lib/apt/lists/"
UPDATE_PKG_CACHE="$PKG_MANAGER update"
PKG_UPDATE="$PKG_MANAGER upgrade"
PKG_INSTALL="$PKG_MANAGER --yes --fix-missing install"
UPDATE_PKG_CACHE="${PKG_MANAGER} update"
PKG_UPDATE="${PKG_MANAGER} upgrade"
PKG_INSTALL="${PKG_MANAGER} --yes --fix-missing install"
# grep -c will return 1 retVal on 0 matches, block this throwing the set -e with an OR TRUE
PKG_COUNT="$PKG_MANAGER -s -o Debug::NoLocking=true upgrade | grep -c ^Inst || true"
PKG_COUNT="${PKG_MANAGER} -s -o Debug::NoLocking=true upgrade | grep -c ^Inst || true"
INSTALLER_DEPS=( apt-utils whiptail git dhcpcd5)
PIHOLE_DEPS=( dnsutils bc dnsmasq lighttpd ${phpVer}-common ${phpVer}-cgi curl unzip wget sudo netcat cron iproute2 )
LIGHTTPD_USER="www-data"
@ -88,20 +89,20 @@ if [ -x "$(command -v apt-get)" ];then
LIGHTTPD_CFG="lighttpd.conf.debian"
DNSMASQ_USER="dnsmasq"
package_check_install() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -c "ok installed" || ${PKG_INSTALL} "$1"
dpkg-query -W -f='${Status}' "${1}" 2>/dev/null | grep -c "ok installed" || ${PKG_INSTALL} "${1}"
}
elif [ -x "$(command -v rpm)" ];then
elif [ -x "$(command -v rpm)" ]; then
# Fedora Family
if [ -x "$(command -v dnf)" ];then
if [ -x "$(command -v dnf)" ]; then
PKG_MANAGER="dnf"
else
PKG_MANAGER="yum"
fi
PKG_CACHE="/var/cache/$PKG_MANAGER"
UPDATE_PKG_CACHE="$PKG_MANAGER check-update"
PKG_UPDATE="$PKG_MANAGER update -y"
PKG_INSTALL="$PKG_MANAGER install -y"
PKG_COUNT="$PKG_MANAGER check-update | egrep '(.i686|.x86|.noarch|.arm|.src)' | wc -l"
PKG_CACHE="/var/cache/${PKG_MANAGER}"
UPDATE_PKG_CACHE="${PKG_MANAGER} check-update"
PKG_UPDATE="${PKG_MANAGER} update -y"
PKG_INSTALL="${PKG_MANAGER} install -y"
PKG_COUNT="${PKG_MANAGER} check-update | egrep '(.i686|.x86|.noarch|.arm|.src)' | wc -l"
INSTALLER_DEPS=( iproute net-tools procps-ng newt git )
PIHOLE_DEPS=( epel-release bind-utils bc dnsmasq lighttpd lighttpd-fastcgi php-common php-cli php curl unzip wget findutils cronie sudo nmap-ncat )
if grep -q 'Fedora' /etc/redhat-release; then
@ -113,7 +114,7 @@ elif [ -x "$(command -v rpm)" ];then
LIGHTTPD_CFG="lighttpd.conf.fedora"
DNSMASQ_USER="nobody"
package_check_install() {
rpm -qa | grep ^"$1"- > /dev/null || ${PKG_INSTALL} "$1"
rpm -qa | grep ^"${1}"- > /dev/null || ${PKG_INSTALL} "${1}"
}
else
echo "OS distribution not supported"
@ -123,16 +124,16 @@ fi
####### FUNCTIONS ##########
spinner() {
local pid=$1
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "$pid")" ]; do
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "${pid}")" ]; do
local temp=${spinstr#?}
printf " [%c] " "$spinstr"
local spinstr=${temp}${spinstr%"$temp"}
sleep ${delay}
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
printf " [%c] " "${spinstr}"
local spinstr=${temp}${spinstr%"$temp"}
sleep ${delay}
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
}
find_IPv4_information() {
@ -143,7 +144,7 @@ find_IPv4_information() {
}
get_available_interfaces() {
# Get available interfaces. Consider only getting UP interfaces in the future, and leaving DOWN interfaces out of list.
# Get available interfaces. Consider only getting UP interfaces in the future, and leaving DOWN interfaces out of list.
availableInterfaces=$(ip -o link | awk '{print $2}' | grep -v "lo" | cut -d':' -f1 | cut -d'@' -f1)
}
@ -170,21 +171,21 @@ verifyFreeDiskSpace() {
local existing_free_kilobytes=$(df -Pk | grep -m1 '\/$' | awk '{print $4}')
# - Unknown free disk space , not a integer
if ! [[ "$existing_free_kilobytes" =~ ^([0-9])+$ ]]; then
echo "::: Unknown free disk space!"
echo "::: We were unable to determine available free disk space on this system."
echo "::: You may override this check and force the installation, however, it is not recommended"
echo "::: To do so, pass the argument '--i_do_not_follow_recommendations' to the install script"
echo "::: eg. curl -L https://install.pi-hole.net | bash /dev/stdin --i_do_not_follow_recommendations"
exit 1
if ! [[ "${existing_free_kilobytes}" =~ ^([0-9])+$ ]]; then
echo "::: Unknown free disk space!"
echo "::: We were unable to determine available free disk space on this system."
echo "::: You may override this check and force the installation, however, it is not recommended"
echo "::: To do so, pass the argument '--i_do_not_follow_recommendations' to the install script"
echo "::: eg. curl -L https://install.pi-hole.net | bash /dev/stdin --i_do_not_follow_recommendations"
exit 1
# - Insufficient free disk space
elif [[ ${existing_free_kilobytes} -lt ${required_free_kilobytes} ]]; then
echo "::: Insufficient Disk Space!"
echo "::: Your system appears to be low on disk space. pi-hole recommends a minimum of $required_free_kilobytes KiloBytes."
echo "::: You only have $existing_free_kilobytes KiloBytes free."
echo "::: If this is a new install you may need to expand your disk."
echo "::: Try running 'sudo raspi-config', and choose the 'expand file system option'"
echo "::: After rebooting, run this installation again. (curl -L https://install.pi-hole.net | bash)"
echo "::: Insufficient Disk Space!"
echo "::: Your system appears to be low on disk space. pi-hole recommends a minimum of $required_free_kilobytes KiloBytes."
echo "::: You only have ${existing_free_kilobytes} KiloBytes free."
echo "::: If this is a new install you may need to expand your disk."
echo "::: Try running 'sudo raspi-config', and choose the 'expand file system option'"
echo "::: After rebooting, run this installation again. (curl -L https://install.pi-hole.net | bash)"
echo "Insufficient free space, exiting..."
exit 1
@ -206,23 +207,21 @@ chooseInterface() {
# Loop sentinel variable
local firstLoop=1
while read -r line
do
while read -r line; do
mode="OFF"
if [[ ${firstLoop} -eq 1 ]]; then
firstLoop=0
mode="ON"
fi
interfacesArray+=("$line" "available" "$mode")
done <<< "$availableInterfaces"
interfacesArray+=("${line}" "available" "${mode}")
done <<< "${availableInterfaces}"
# Find out how many interfaces are available to choose from
interfaceCount=$(echo "$availableInterfaces" | wc -l)
interfaceCount=$(echo "${availableInterfaces}" | wc -l)
chooseInterfaceCmd=(whiptail --separate-output --radiolist "Choose An Interface (press space to select)" ${r} ${c} ${interfaceCount})
chooseInterfaceOptions=$("${chooseInterfaceCmd[@]}" "${interfacesArray[@]}" 2>&1 >/dev/tty)
if [[ $? = 0 ]]; then
for desiredInterface in ${chooseInterfaceOptions}
do
for desiredInterface in ${chooseInterfaceOptions}; do
piholeInterface=${desiredInterface}
echo "::: Using interface: $piholeInterface"
done
@ -256,15 +255,15 @@ use4andor6() {
esac
done
if [[ ${useIPv4} ]]; then
find_IPv4_information
getStaticIPv4Settings
setStaticIPv4
find_IPv4_information
getStaticIPv4Settings
setStaticIPv4
fi
if [[ ${useIPv6} ]]; then
useIPv6dialog
fi
echo "::: IPv4 address: ${IPv4_address}"
echo "::: IPv6 address: ${IPv6_address}"
useIPv6dialog
fi
echo "::: IPv4 address: ${IPv4_address}"
echo "::: IPv6 address: ${IPv6_address}"
if [ ! ${useIPv4} ] && [ ! ${useIPv6} ]; then
echo "::: Cannot continue, neither IPv4 or IPv6 selected"
echo "::: Exiting"
@ -279,8 +278,8 @@ use4andor6() {
getStaticIPv4Settings() {
# Ask if the user wants to use DHCP settings as their static IP
if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Do you want to use your current network settings as a static address?
IP address: $IPv4_address
Gateway: $IPv4gw" ${r} ${c}); then
IP address: ${IPv4_address}
Gateway: ${IPv4gw}" ${r} ${c}); then
# If they choose yes, let the user know that the IP address will not be available via DHCP and may cause a conflict.
whiptail --msgbox --backtitle "IP information" --title "FYI: IP Conflict" "It is possible your router could still try to assign this IP to a device, which would cause a conflict. But in most cases the router is smart enough to not do that.
If you are worried, either manually set the address, or modify the DHCP reservation pool so it does not include the IP you want.
@ -290,20 +289,19 @@ It is also possible to use a DHCP reservation, but if you are going to do that,
# Otherwise, we need to ask the user to input their desired settings.
# Start by getting the IPv4 address (pre-filling it with info gathered from DHCP)
# Start a loop to let the user enter their information with the chance to go back and edit it if necessary
until [[ ${ipSettingsCorrect} = True ]]
do
until [[ ${ipSettingsCorrect} = True ]]; do
# Ask for the IPv4 address
IPv4_address=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" ${r} ${c} "$IPv4_address" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]];then
echo "::: Your static IPv4 address: $IPv4_address"
IPv4_address=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 address" --inputbox "Enter your desired IPv4 address" ${r} ${c} "${IPv4_address}" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]]; then
echo "::: Your static IPv4 address: ${IPv4_address}"
# Ask for the gateway
IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" ${r} ${c} "$IPv4gw" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]];then
echo "::: Your static IPv4 gateway: $IPv4gw"
IPv4gw=$(whiptail --backtitle "Calibrating network interface" --title "IPv4 gateway (router)" --inputbox "Enter your desired IPv4 default gateway" ${r} ${c} "${IPv4gw}" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]]; then
echo "::: Your static IPv4 gateway: ${IPv4gw}"
# Give the user a chance to review their settings before moving on
if (whiptail --backtitle "Calibrating network interface" --title "Static IP Address" --yesno "Are these settings correct?
IP address: $IPv4_address
Gateway: $IPv4gw" ${r} ${c}); then
IP address: ${IPv4_address}
Gateway: ${IPv4gw}" ${r} ${c}); then
# After that's done, the loop ends and we move on
ipSettingsCorrect=True
else
@ -329,31 +327,31 @@ It is also possible to use a DHCP reservation, but if you are going to do that,
setDHCPCD() {
# Append these lines to dhcpcd.conf to enable a static IP
echo "## interface $piholeInterface
static ip_address=$IPv4_address
static routers=$IPv4gw
static domain_name_servers=$IPv4gw" | tee -a /etc/dhcpcd.conf >/dev/null
echo "## interface ${piholeInterface}
static ip_address=${IPv4_address}
static routers=${IPv4gw}
static domain_name_servers=${IPv4gw}" | tee -a /etc/dhcpcd.conf >/dev/null
}
setStaticIPv4() {
local IFCFG_FILE
local IPADDR
local CIDR
if [[ -f /etc/dhcpcd.conf ]];then
local IFCFG_FILE
local IPADDR
local CIDR
if [[ -f /etc/dhcpcd.conf ]]; then
# Debian Family
if grep -q "$IPv4_address" /etc/dhcpcd.conf; then
if grep -q "${IPv4_address}" /etc/dhcpcd.conf; then
echo "::: Static IP already configured"
else
setDHCPCD
ip addr replace dev "$piholeInterface" "$IPv4_address"
ip addr replace dev "${piholeInterface}" "${IPv4_address}"
echo ":::"
echo "::: Setting IP to $IPv4_address. You may need to restart after the install is complete."
echo "::: Setting IP to ${IPv4_address}. You may need to restart after the install is complete."
echo ":::"
fi
elif [[ -f /etc/sysconfig/network-scripts/ifcfg-${piholeInterface} ]];then
# Fedora Family
IFCFG_FILE=/etc/sysconfig/network-scripts/ifcfg-${piholeInterface}
if grep -q "$IPv4_address" "${IFCFG_FILE}"; then
if grep -q "${IPv4_address}" "${IFCFG_FILE}"; then
echo "::: Static IP already configured"
else
IPADDR=$(echo "${IPv4_address}" | cut -f1 -d/)
@ -362,18 +360,18 @@ setStaticIPv4() {
cp "${IFCFG_FILE}" "${IFCFG_FILE}".pihole.orig
# Build Interface configuration file:
{
echo "# Configured via Pi-Hole installer"
echo "DEVICE=$piholeInterface"
echo "BOOTPROTO=none"
echo "ONBOOT=yes"
echo "IPADDR=$IPADDR"
echo "PREFIX=$CIDR"
echo "GATEWAY=$IPv4gw"
echo "DNS1=$piholeDNS1"
echo "DNS2=$piholeDNS2"
echo "USERCTL=no"
echo "# Configured via Pi-Hole installer"
echo "DEVICE=$piholeInterface"
echo "BOOTPROTO=none"
echo "ONBOOT=yes"
echo "IPADDR=$IPADDR"
echo "PREFIX=$CIDR"
echo "GATEWAY=$IPv4gw"
echo "DNS1=$piholeDNS1"
echo "DNS2=$piholeDNS2"
echo "USERCTL=no"
}>> "${IFCFG_FILE}"
ip addr replace dev "$piholeInterface" "$IPv4_address"
ip addr replace dev "${piholeInterface}" "${IPv4_address}"
if [ -x "$(command -v nmcli)" ];then
# Tell NetworkManager to read our new sysconfig file
nmcli con load "${IFCFG_FILE}" > /dev/null
@ -389,8 +387,8 @@ setStaticIPv4() {
}
valid_ip() {
local ip=$1
local stat=1
local ip=${1}
local stat=1
if [[ ${ip} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
@ -415,80 +413,80 @@ setDNS() {
DNSchoices=$("${DNSChooseCmd[@]}" "${DNSChooseOptions[@]}" 2>&1 >/dev/tty)
if [[ $? = 0 ]];then
case ${DNSchoices} in
Google)
echo "::: Using Google DNS servers."
piholeDNS1="8.8.8.8"
piholeDNS2="8.8.4.4"
;;
OpenDNS)
echo "::: Using OpenDNS servers."
piholeDNS1="208.67.222.222"
piholeDNS2="208.67.220.220"
;;
Level3)
echo "::: Using Level3 servers."
piholeDNS1="4.2.2.1"
piholeDNS2="4.2.2.2"
;;
Norton)
echo "::: Using Norton ConnectSafe servers."
piholeDNS1="199.85.126.10"
piholeDNS2="199.85.127.10"
;;
Comodo)
echo "::: Using Comodo Secure servers."
piholeDNS1="8.26.56.26"
piholeDNS2="8.20.247.20"
;;
Custom)
until [[ ${DNSSettingsCorrect} = True ]]
do
strInvalid="Invalid"
if [ ! ${piholeDNS1} ]; then
if [ ! ${piholeDNS2} ]; then
prePopulate=""
else
prePopulate=", $piholeDNS2"
fi
elif [ ${piholeDNS1} ] && [ ! ${piholeDNS2} ]; then
prePopulate="$piholeDNS1"
elif [ ${piholeDNS1} ] && [ ${piholeDNS2} ]; then
prePopulate="$piholeDNS1, $piholeDNS2"
fi
piholeDNS=$(whiptail --backtitle "Specify Upstream DNS Provider(s)" --inputbox "Enter your desired upstream DNS provider(s), seperated by a comma.\n\nFor example '8.8.8.8, 8.8.4.4'" ${r} ${c} "$prePopulate" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]];then
piholeDNS1=$(echo "$piholeDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}')
piholeDNS2=$(echo "$piholeDNS" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}')
if ! valid_ip "$piholeDNS1" || [ ! "$piholeDNS1" ]; then
piholeDNS1=${strInvalid}
fi
if ! valid_ip "$piholeDNS2" && [ "$piholeDNS2" ]; then
piholeDNS2=${strInvalid}
fi
else
echo "::: Cancel selected, exiting...."
exit 1
fi
if [[ ${piholeDNS1} == "$strInvalid" ]] || [[ ${piholeDNS2} == "$strInvalid" ]]; then
whiptail --msgbox --backtitle "Invalid IP" --title "Invalid IP" "One or both entered IP addresses were invalid. Please try again.\n\n DNS Server 1: $piholeDNS1\n DNS Server 2: $piholeDNS2" ${r} ${c}
if [[ ${piholeDNS1} == "$strInvalid" ]]; then
piholeDNS1=""
fi
if [[ ${piholeDNS2} == "$strInvalid" ]]; then
piholeDNS2=""
fi
DNSSettingsCorrect=False
else
if (whiptail --backtitle "Specify Upstream DNS Provider(s)" --title "Upstream DNS Provider(s)" --yesno "Are these settings correct?\n DNS Server 1: $piholeDNS1\n DNS Server 2: $piholeDNS2" ${r} ${c}); then
DNSSettingsCorrect=True
else
# If the settings are wrong, the loop continues
DNSSettingsCorrect=False
fi
fi
done
;;
esac
Google)
echo "::: Using Google DNS servers."
piholeDNS1="8.8.8.8"
piholeDNS2="8.8.4.4"
;;
OpenDNS)
echo "::: Using OpenDNS servers."
piholeDNS1="208.67.222.222"
piholeDNS2="208.67.220.220"
;;
Level3)
echo "::: Using Level3 servers."
piholeDNS1="4.2.2.1"
piholeDNS2="4.2.2.2"
;;
Norton)
echo "::: Using Norton ConnectSafe servers."
piholeDNS1="199.85.126.10"
piholeDNS2="199.85.127.10"
;;
Comodo)
echo "::: Using Comodo Secure servers."
piholeDNS1="8.26.56.26"
piholeDNS2="8.20.247.20"
;;
Custom)
until [[ ${DNSSettingsCorrect} = True ]]; do
strInvalid="Invalid"
if [ ! ${piholeDNS1} ]; then
if [ ! ${piholeDNS2} ]; then
prePopulate=""
else
prePopulate=", ${piholeDNS2}"
fi
elif [ ${piholeDNS1} ] && [ ! ${piholeDNS2} ]; then
prePopulate="${piholeDNS1}"
elif [ ${piholeDNS1} ] && [ ${piholeDNS2} ]; then
prePopulate="${piholeDNS1}, ${piholeDNS2}"
fi
piholeDNS=$(whiptail --backtitle "Specify Upstream DNS Provider(s)" --inputbox "Enter your desired upstream DNS provider(s), seperated by a comma.\n\nFor example '8.8.8.8, 8.8.4.4'" ${r} ${c} "${prePopulate}" 3>&1 1>&2 2>&3)
if [[ $? = 0 ]]; then
piholeDNS1=$(echo "${piholeDNS}" | sed 's/[, \t]\+/,/g' | awk -F, '{print$1}')
piholeDNS2=$(echo "${piholeDNS}" | sed 's/[, \t]\+/,/g' | awk -F, '{print$2}')
if ! valid_ip "${piholeDNS1}" || [ ! "${piholeDNS1}" ]; then
piholeDNS1=${strInvalid}
fi
if ! valid_ip "${piholeDNS2}" && [ "${piholeDNS2}" ]; then
piholeDNS2=${strInvalid}
fi
else
echo "::: Cancel selected, exiting...."
exit 1
fi
if [[ ${piholeDNS1} == "${strInvalid}" ]] || [[ ${piholeDNS2} == "${strInvalid}" ]]; then
whiptail --msgbox --backtitle "Invalid IP" --title "Invalid IP" "One or both entered IP addresses were invalid. Please try again.\n\n DNS Server 1: $piholeDNS1\n DNS Server 2: ${piholeDNS2}" ${r} ${c} if [[ ${piholeDNS1} == "${strInvalid}" ]]; then
piholeDNS1=""
fi
if [[ ${piholeDNS2} == "${strInvalid}" ]]; then
piholeDNS2=""
fi
DNSSettingsCorrect=False
else
if (whiptail --backtitle "Specify Upstream DNS Provider(s)" --title "Upstream DNS Provider(s)" --yesno "Are these settings correct?\n DNS Server 1: $piholeDNS1\n DNS Server 2: ${piholeDNS2}" ${r} ${c}); then
DNSSettingsCorrect=True
else
# If the settings are wrong, the loop continues
DNSSettingsCorrect=False
fi
fi
done
;;
esac
else
echo "::: Cancel selected. Exiting..."
exit 1
@ -527,12 +525,12 @@ version_check_dnsmasq() {
cp ${dnsmasq_pihole_01_snippet} ${dnsmasq_pihole_01_location}
echo " done."
sed -i "s/@INT@/$piholeInterface/" ${dnsmasq_pihole_01_location}
if [[ "$piholeDNS1" != "" ]]; then
if [[ "${piholeDNS1}" != "" ]]; then
sed -i "s/@DNS1@/$piholeDNS1/" ${dnsmasq_pihole_01_location}
else
sed -i '/^server=@DNS1@/d' ${dnsmasq_pihole_01_location}
fi
if [[ "$piholeDNS2" != "" ]]; then
if [[ "${piholeDNS2}" != "" ]]; then
sed -i "s/@DNS2@/$piholeDNS2/" ${dnsmasq_pihole_01_location}
else
sed -i '/^server=@DNS2@/d' ${dnsmasq_pihole_01_location}
@ -573,7 +571,7 @@ installConfigs() {
version_check_dnsmasq
if [ ! -d "/etc/lighttpd" ]; then
mkdir /etc/lighttpd
chown "$USER":root /etc/lighttpd
chown "${USER}":root /etc/lighttpd
mv /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.orig
fi
cp /etc/.pihole/advanced/${LIGHTTPD_CFG} /etc/lighttpd/lighttpd.conf
@ -597,8 +595,8 @@ stop_service() {
}
start_service() {
# Start/Restart service passed in as argument
# This should not fail, it's an error if it does
# Start/Restart service passed in as argument
# This should not fail, it's an error if it does
echo ":::"
echo -n "::: Starting ${1} service..."
if [ -x "$(command -v systemctl)" ]; then
@ -610,7 +608,7 @@ start_service() {
}
enable_service() {
# Enable service so that it will start with next reboot
# Enable service so that it will start with next reboot
echo ":::"
echo -n "::: Enabling ${1} service to start on reboot..."
if [ -x "$(command -v systemctl)" ]; then
@ -628,13 +626,13 @@ update_pacakge_cache() {
#Check to see if apt-get update has already been run today
#it needs to have been run at least once on new installs!
timestamp=$(stat -c %Y ${PKG_CACHE})
timestampAsDate=$(date -d @"$timestamp" "+%b %e")
timestampAsDate=$(date -d @"${timestamp}" "+%b %e")
today=$(date "+%b %e")
if [ ! "$today" == "$timestampAsDate" ]; then
if [ ! "${today}" == "${timestampAsDate}" ]; then
#update package lists
echo ":::"
echo -n "::: $PKG_MANAGER update has not been run today. Running now..."
echo -n "::: ${PKG_MANAGER} update has not been run today. Running now..."
${UPDATE_PKG_CACHE} &> /dev/null & spinner $!
echo " done!"
fi
@ -644,23 +642,23 @@ notify_package_updates_available() {
# Let user know if they have outdated packages on their system and
# advise them to run a package update at soonest possible.
echo ":::"
echo -n "::: Checking $PKG_MANAGER for upgraded packages...."
echo -n "::: Checking ${PKG_MANAGER} for upgraded packages...."
updatesToInstall=$(eval "${PKG_COUNT}")
echo " done!"
echo ":::"
if [[ ${updatesToInstall} -eq "0" ]]; then
echo "::: Your system is up to date! Continuing with Pi-hole installation..."
else
echo "::: There are $updatesToInstall updates available for your system!"
echo "::: We recommend you run '$PKG_UPDATE' after installing Pi-Hole! "
echo "::: There are ${updatesToInstall} updates available for your system!"
echo "::: We recommend you run '${PKG_UPDATE}' after installing Pi-Hole! "
echo ":::"
fi
}
install_dependent_packages() {
# Install packages passed in via argument array
# No spinner - conflicts with set -e
declare -a argArray1=("${!1}")
# Install packages passed in via argument array
# No spinner - conflicts with set -e
declare -a argArray1=("${!1}")
for i in "${argArray1[@]}"; do
echo -n "::: Checking for $i..."
@ -678,37 +676,37 @@ getGitFiles() {
update_repo "${1}"
else
make_repo "${1}" "${2}"
fi
fi
}
is_repo() {
# Use git to check if directory is currently under VCS
# Use git to check if directory is currently under VCS
echo -n "::: Checking $1 is a repo..."
cd "${1}" &> /dev/null || return 1
git status &> /dev/null && echo " OK!"; return 0 || echo " not found!"; return 1
}
make_repo() {
# Remove the non-repod interface and clone the interface
echo -n "::: Cloning $2 into $1..."
rm -rf "${1}"
git clone -q --depth 1 "${2}" "${1}" > /dev/null & spinner $!
echo " done!"
# Remove the non-repod interface and clone the interface
echo -n "::: Cloning $2 into $1..."
rm -rf "${1}"
git clone -q --depth 1 "${2}" "${1}" > /dev/null & spinner $!
echo " done!"
}
update_repo() {
# Pull the latest commits
echo -n "::: Updating repo in $1..."
cd "${1}" || exit 1
git stash -q > /dev/null & spinner $!
git pull -q > /dev/null & spinner $!
echo " done!"
# Pull the latest commits
echo -n "::: Updating repo in $1..."
cd "${1}" || exit 1
git stash -q > /dev/null & spinner $!
git pull -q > /dev/null & spinner $!
echo " done!"
}
CreateLogFile() {
# Create logfiles if necessary
echo ":::"
echo -n "::: Creating log file and changing owner to dnsmasq..."
echo -n "::: Creating log file and changing owner to dnsmasq..."
if [ ! -f /var/log/pihole.log ]; then
touch /var/log/pihole.log
chmod 644 /var/log/pihole.log
@ -785,60 +783,59 @@ configureFirewall() {
}
finalExports() {
#If it already exists, lets overwrite it with the new values.
if [[ -f ${setupVars} ]];then
rm ${setupVars}
fi
#If it already exists, lets overwrite it with the new values.
if [[ -f ${setupVars} ]]; then
rm ${setupVars}
fi
{
echo "piholeInterface=${piholeInterface}"
echo "IPv4_address=${IPv4_address}"
echo "IPv6_address=${IPv6_address}"
echo "piholeDNS1=${piholeDNS1}"
echo "piholeDNS2=${piholeDNS2}"
echo "piholeInterface=${piholeInterface}"
echo "IPv4_address=${IPv4_address}"
echo "IPv6_address=${IPv6_address}"
echo "piholeDNS1=${piholeDNS1}"
echo "piholeDNS2=${piholeDNS2}"
}>> "${setupVars}"
}
installPihole() {
# Install base files and web interface
create_pihole_user
if [ ! -d "/var/www/html" ]; then
mkdir -p /var/www/html
fi
chown ${LIGHTTPD_USER}:${LIGHTTPD_GROUP} /var/www/html
chmod 775 /var/www/html
usermod -a -G ${LIGHTTPD_GROUP} pihole
if [ -x "$(command -v lighty-enable-mod)" ]; then
lighty-enable-mod fastcgi fastcgi-php > /dev/null || true
else
printf "\n:::\tWarning: 'lighty-enable-mod' utility not found. Please ensure fastcgi is enabled if you experience issues.\n"
fi
installScripts
installConfigs
CreateLogFile
configureSelinux
installPiholeWeb
installCron
configureFirewall
finalExports
runGravity
# Install base files and web interface
create_pihole_user
if [ ! -d "/var/www/html" ]; then
mkdir -p /var/www/html
fi
chown ${LIGHTTPD_USER}:${LIGHTTPD_GROUP} /var/www/html
chmod 775 /var/www/html
usermod -a -G ${LIGHTTPD_GROUP} pihole
if [ -x "$(command -v lighty-enable-mod)" ]; then
lighty-enable-mod fastcgi fastcgi-php > /dev/null || true
else
printf "\n:::\tWarning: 'lighty-enable-mod' utility not found. Please ensure fastcgi is enabled if you experience issues.\n"
fi
installScripts
installConfigs
CreateLogFile
configureSelinux
installPiholeWeb
installCron
configureFirewall
finalExports
runGravity
}
updatePihole() {
# Refactoring of install script has changed the name of a couple of variables. Sort them out here.
sed -i 's/IPv4addr/IPv4_address/g' ${setupVars}
sed -i 's/piholeIPv6/IPv6_address/g' ${setupVars}
# Source ${setupVars} for use in the rest of the functions.
. ${setupVars}
# Install base files and web interface
installScripts
installConfigs
CreateLogFile
configureSelinux
installPiholeWeb
installCron
configureFirewall
runGravity
# Refactoring of install script has changed the name of a couple of variables. Sort them out here.
sed -i 's/IPv4addr/IPv4_address/g' ${setupVars}
sed -i 's/piholeIPv6/IPv6_address/g' ${setupVars}
# Source ${setupVars} for use in the rest of the functions.
. ${setupVars}
# Install base files and web interface
installScripts
installConfigs
CreateLogFile
configureSelinux
installPiholeWeb
installCron
configureFirewall
runGravity
}
configureSelinux() {
@ -866,7 +863,7 @@ displayFinalMessage() {
whiptail --msgbox --backtitle "Make it so." --title "Installation Complete!" "Configure your devices to use the Pi-hole as their DNS server using:
IPv4: ${IPv4_address%/*}
IPv6: $IPv6_address
IPv6: ${IPv6_address}
If you set a new IP address, you should restart the Pi.
@ -875,142 +872,141 @@ View the web interface at http://pi.hole/admin or http://${IPv4_address%/*}/admi
}
update_dialogs() {
# reconfigure
if [ "$reconfigure" = true ]; then
opt1a="Repair"
opt1b="This will retain existing settings"
strAdd="You will remain on the same version"
else
opt1a="Update"
opt1b="This will retain existing settings."
strAdd="You will be updated to the latest version."
fi
opt2a="Reconfigure"
opt2b="This will allow you to enter new settings"
# reconfigure
if [ "${reconfigure}" = true ]; then
opt1a="Repair"
opt1b="This will retain existing settings"
strAdd="You will remain on the same version"
else
opt1a="Update"
opt1b="This will retain existing settings."
strAdd="You will be updated to the latest version."
fi
opt2a="Reconfigure"
opt2b="This will allow you to enter new settings"
UpdateCmd=$(whiptail --title "Existing Install Detected!" --menu "\n\nWe have detected an existing install.\n\nPlease choose from the following options: \n($strAdd)" ${r} ${c} 2 \
"$opt1a" "$opt1b" \
"$opt2a" "$opt2b" 3>&2 2>&1 1>&3)
UpdateCmd=$(whiptail --title "Existing Install Detected!" --menu "\n\nWe have detected an existing install.\n\nPlease choose from the following options: \n($strAdd)" ${r} ${c} 2 \
"${opt1a}" "${opt1b}" \
"${opt2a}" "${opt2b}" 3>&2 2>&1 1>&3)
if [[ $? = 0 ]];then
case ${UpdateCmd} in
${opt1a})
echo "::: $opt1a option selected."
useUpdateVars=true
;;
${opt2a})
echo "::: $opt2a option selected"
useUpdateVars=false
;;
esac
else
echo "::: Cancel selected. Exiting..."
exit 1
fi
if [[ $? = 0 ]];then
case ${UpdateCmd} in
${opt1a})
echo "::: ${opt1a} option selected."
useUpdateVars=true
;;
${opt2a})
echo "::: ${opt2a} option selected"
useUpdateVars=false
;;
esac
else
echo "::: Cancel selected. Exiting..."
exit 1
fi
}
main() {
# Check arguments for the undocumented flags
for var in "$@"
do
case "$var" in
"--reconfigure" ) reconfigure=true;;
"--i_do_not_follow_recommendations" ) skipSpaceCheck=false;;
"--unattended" ) runUnattended=true;;
esac
done
for var in "$@"; do
case "$var" in
"--reconfigure" ) reconfigure=true;;
"--i_do_not_follow_recommendations" ) skipSpaceCheck=false;;
"--unattended" ) runUnattended=true;;
esac
done
if [[ -f ${setupVars} ]];then
if [[ "${runUnattended}" == true ]]; then
echo "::: --unattended passed to install script, no whiptail dialogs will be displayed"
useUpdateVars=true
else
update_dialogs
fi
fi
if [[ -f ${setupVars} ]]; then
if [[ "${runUnattended}" == true ]]; then
echo "::: --unattended passed to install script, no whiptail dialogs will be displayed"
useUpdateVars=true
else
update_dialogs
fi
fi
# Start the installer
# Verify there is enough disk space for the install
if [[ "${skipSpaceCheck}" == true ]]; then
echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!"
else
verifyFreeDiskSpace
fi
# Start the installer
# Verify there is enough disk space for the install
if [[ "${skipSpaceCheck}" == true ]]; then
echo "::: --i_do_not_follow_recommendations passed to script, skipping free disk space verification!"
else
verifyFreeDiskSpace
fi
# Update package cache
update_pacakge_cache
# Update package cache
update_pacakge_cache
# Notify user of package availability
notify_package_updates_available
# Notify user of package availability
notify_package_updates_available
# Install packages used by this installation script
install_dependent_packages INSTALLER_DEPS[@]
# Install packages used by this installation script
install_dependent_packages INSTALLER_DEPS[@]
# Install packages used by the Pi-hole
install_dependent_packages PIHOLE_DEPS[@]
# Install packages used by the Pi-hole
install_dependent_packages PIHOLE_DEPS[@]
if [[ "${reconfigure}" == true ]]; then
echo "::: --reconfigure passed to install script. Not downloading/updating local repos"
else
# Get Git files for Core and Admin
getGitFiles ${piholeFilesDir} ${piholeGitUrl}
getGitFiles ${webInterfaceDir} ${webInterfaceGitUrl}
fi
if [[ "${reconfigure}" == true ]]; then
echo "::: --reconfigure passed to install script. Not downloading/updating local repos"
else
# Get Git files for Core and Admin
getGitFiles ${piholeFilesDir} ${piholeGitUrl}
getGitFiles ${webInterfaceDir} ${webInterfaceGitUrl}
fi
if [[ ${useUpdateVars} == false ]]; then
# Display welcome dialogs
welcomeDialogs
# Create directory for Pi-hole storage
mkdir -p /etc/pihole/
# Remove legacy scripts from previous storage location
remove_legacy_scripts
# Stop resolver and webserver while installing proceses
stop_service dnsmasq
stop_service lighttpd
# Determine available interfaces
get_available_interfaces
# Find interfaces and let the user choose one
chooseInterface
# Let the user decide if they want to block ads over IPv4 and/or IPv6
use4andor6
# Decide what upstream DNS Servers to use
setDNS
# Install and log everything to a file
installPihole | tee ${tmpLog}
else
updatePihole | tee ${tmpLog}
fi
if [[ ${useUpdateVars} == false ]]; then
# Display welcome dialogs
welcomeDialogs
# Create directory for Pi-hole storage
mkdir -p /etc/pihole/
# Remove legacy scripts from previous storage location
remove_legacy_scripts
# Stop resolver and webserver while installing proceses
stop_service dnsmasq
stop_service lighttpd
# Determine available interfaces
get_available_interfaces
# Find interfaces and let the user choose one
chooseInterface
# Let the user decide if they want to block ads over IPv4 and/or IPv6
use4andor6
# Decide what upstream DNS Servers to use
setDNS
# Install and log everything to a file
installPihole | tee ${tmpLog}
else
updatePihole | tee ${tmpLog}
fi
# Move the log file into /etc/pihole for storage
mv ${tmpLog} ${instalLogLoc}
# Move the log file into /etc/pihole for storage
mv ${tmpLog} ${instalLogLoc}
if [[ "${useUpdateVars}" == false ]]; then
displayFinalMessage
fi
if [[ "${useUpdateVars}" == false ]]; then
displayFinalMessage
fi
echo "::: Restarting services..."
# Start services
start_service dnsmasq
enable_service dnsmasq
start_service lighttpd
enable_service lighttpd
echo "::: done."
echo "::: Restarting services..."
# Start services
start_service dnsmasq
enable_service dnsmasq
start_service lighttpd
enable_service lighttpd
echo "::: done."
echo ":::"
if [[ "${useUpdateVars}" == false ]]; then
echo "::: Installation Complete! Configure your devices to use the Pi-hole as their DNS server using:"
echo "::: ${IPv4_address%/*}"
echo "::: $IPv6_address"
echo ":::"
echo "::: If you set a new IP address, you should restart the Pi."
else
echo "::: Update complete!"
fi
echo ":::"
if [[ "${useUpdateVars}" == false ]]; then
echo "::: Installation Complete! Configure your devices to use the Pi-hole as their DNS server using:"
echo "::: ${IPv4_address%/*}"
echo "::: ${IPv6_address}"
echo ":::"
echo "::: If you set a new IP address, you should restart the Pi."
else
echo "::: Update complete!"
fi
echo ":::"
echo "::: The install log is located at: /etc/pihole/install.log"
echo "::: View the web interface at http://pi.hole/admin or http://${IPv4_address%/*}/admin"
echo ":::"
echo "::: The install log is located at: /etc/pihole/install.log"
echo "::: View the web interface at http://pi.hole/admin or http://${IPv4_address%/*}/admin"
}
main "$@"

View File

@ -11,29 +11,29 @@
# (at your option) any later version.
# Must be root to uninstall
if [[ $EUID -eq 0 ]];then
if [[ ${EUID} -eq 0 ]]; then
echo "::: You are root."
else
echo "::: Sudo will be used for the uninstall."
# Check if it is actually installed
# If it isn't, exit because the unnstall cannot complete
if [ -x "$(command -v sudo)" ];then
# Check if it is actually installed
# If it isn't, exit because the unnstall cannot complete
if [ -x "$(command -v sudo)" ]; then
export SUDO="sudo"
else
echo "::: Please install sudo or run this as root."
exit 1
fi
else
echo "::: Please install sudo or run this as root."
exit 1
fi
fi
# Compatability
if [ -x "$(command -v rpm)" ];then
if [ -x "$(command -v rpm)" ]; then
# Fedora Family
if [ -x "$(command -v dnf)" ];then
if [ -x "$(command -v dnf)" ]; then
PKG_MANAGER="dnf"
else
PKG_MANAGER="yum"
fi
PKG_REMOVE="$PKG_MANAGER remove -y"
PKG_REMOVE="${PKG_MANAGER} remove -y"
PIHOLE_DEPS=( bind-utils bc dnsmasq lighttpd lighttpd-fastcgi php-common git curl unzip wget findutils )
package_check() {
rpm -qa | grep ^$1- > /dev/null
@ -41,10 +41,10 @@ if [ -x "$(command -v rpm)" ];then
package_cleanup() {
${SUDO} ${PKG_MANAGER} -y autoremove
}
elif [ -x "$(command -v apt-get)" ];then
elif [ -x "$(command -v apt-get)" ]; then
# Debian Family
PKG_MANAGER="apt-get"
PKG_REMOVE="$PKG_MANAGER -y remove --purge"
PKG_REMOVE="${PKG_MANAGER} -y remove --purge"
PIHOLE_DEPS=( dnsutils bc dnsmasq lighttpd php5-common git curl unzip wget )
package_check() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -c "ok installed"
@ -59,17 +59,17 @@ else
fi
spinner() {
local pid=$1
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "$pid")" ]; do
local temp=${spinstr#?}
printf " [%c] " "$spinstr"
local spinstr=${temp}${spinstr%"$temp"}
sleep ${delay}
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
local pid=$1
local delay=0.50
local spinstr='/-\|'
while [ "$(ps a | awk '{print $1}' | grep "${pid}")" ]; do
local temp=${spinstr#?}
printf " [%c] " "${spinstr}"
local spinstr=${temp}${spinstr%"$temp}"}
sleep ${delay}
printf "\b\b\b\b\b\b"
done
printf " \b\b\b\b"
}
removeAndPurge() {
@ -79,15 +79,15 @@ removeAndPurge() {
package_check ${i} > /dev/null
if [ $? -eq 0 ]; then
while true; do
read -rp "::: Do you wish to remove $i from your system? [y/n]: " yn
read -rp "::: Do you wish to remove ${i} from your system? [y/n]: " yn
case ${yn} in
[Yy]* ) printf ":::\tRemoving %s..." "$i"; ${SUDO} ${PKG_REMOVE} "$i" &> /dev/null & spinner $!; printf "done!\n"; break;;
[Nn]* ) printf ":::\tSkipping %s" "$i\n"; break;;
[Yy]* ) printf ":::\tRemoving %s..." "${i}"; ${SUDO} ${PKG_REMOVE} "${i}" &> /dev/null & spinner $!; printf "done!\n"; break;;
[Nn]* ) printf ":::\tSkipping %s" "${i}\n"; break;;
* ) printf "::: You must answer yes or no!\n";;
esac
done
else
printf ":::\tPackage %s not installed... Not removing.\n" "$i"
printf ":::\tPackage %s not installed... Not removing.\n" "${i}"
fi
done

View File

@ -35,11 +35,11 @@ blacklistScript=/opt/pihole/blacklist.sh
#Source the setupVars from install script for the IP
setupVars=/etc/pihole/setupVars.conf
if [[ -f ${setupVars} ]];then
. /etc/pihole/setupVars.conf
. /etc/pihole/setupVars.conf
else
echo "::: WARNING: /etc/pihole/setupVars.conf missing. Possible installation failure."
echo "::: Please run 'pihole -r', and choose the 'reconfigure' option to reconfigure."
exit 1
echo "::: WARNING: /etc/pihole/setupVars.conf missing. Possible installation failure."
echo "::: Please run 'pihole -r', and choose the 'reconfigure' option to reconfigure."
exit 1
fi
#Remove the /* from the end of the IPv4addr.
@ -56,8 +56,8 @@ eventHorizon=${basename}.2.eventHorizon.txt
accretionDisc=${basename}.3.accretionDisc.txt
# Warn users still using pihole.conf that it no longer has any effect (I imagine about 2 people use it)
if [[ -r ${piholeDir}/pihole.conf ]];then
echo "::: pihole.conf file no longer supported. Over-rides in this file are ignored."
if [[ -r ${piholeDir}/pihole.conf ]]; then
echo "::: pihole.conf file no longer supported. Over-rides in this file are ignored."
fi
###########################
@ -95,17 +95,17 @@ gravity_collapse() {
fi
# Create the pihole resource directory if it doesn't exist. Future files will be stored here
if [[ -d ${piholeDir} ]];then
# Temporary hack to allow non-root access to pihole directory
# Will update later, needed for existing installs, new installs should
# create this directory as non-root
chmod 777 ${piholeDir}
echo ":::"
echo "::: Existing pihole directory found"
if [[ -d ${piholeDir} ]]; then
# Temporary hack to allow non-root access to pihole directory
# Will update later, needed for existing installs, new installs should
# create this directory as non-root
chmod 777 ${piholeDir}
echo ":::"
echo "::: Existing pihole directory found"
else
echo "::: Creating pihole directory..."
mkdir ${piholeDir}
chmod 777 ${piholeDir}
echo "::: Creating pihole directory..."
mkdir ${piholeDir}
chmod 777 ${piholeDir}
fi
}
@ -113,11 +113,11 @@ gravity_collapse() {
gravity_patternCheck() {
patternBuffer=$1
# check if the patternbuffer is a non-zero length file
if [[ -s "$patternBuffer" ]];then
if [[ -s "${patternBuffer}" ]]; then
# Some of the blocklists are copyright, they need to be downloaded
# and stored as is. They can be processed for content after they
# have been saved.
cp "$patternBuffer" "$saveLocation"
cp "${patternBuffer}" "${saveLocation}"
echo " List updated, transport successful!"
else
# curl didn't download any host files, probably because of the date check
@ -136,51 +136,50 @@ gravity_transport() {
heisenbergCompensator=""
if [[ -r ${saveLocation} ]]; then
# if domain has been saved, add file for date check to only download newer
heisenbergCompensator="-z $saveLocation"
heisenbergCompensator="-z ${saveLocation}"
fi
# Silently curl url
curl -s -L ${cmd_ext} ${heisenbergCompensator} -A "$agent" ${url} > ${patternBuffer}
curl -s -L ${cmd_ext} ${heisenbergCompensator} -A "${agent}" ${url} > ${patternBuffer}
# Check for list updates
gravity_patternCheck "$patternBuffer"
gravity_patternCheck "${patternBuffer}"
# Cleanup
rm -f "$patternBuffer"
rm -f "${patternBuffer}"
}
# spinup - main gravity function
gravity_spinup() {
echo ":::"
# Loop through domain list. Download each one and remove commented lines (lines beginning with '# 'or '/') and # blank lines
for ((i = 0; i < "${#sources[@]}"; i++))
do
url=${sources[$i]}
# Get just the domain from the URL
domain=$(echo "$url" | cut -d'/' -f3)
for ((i = 0; i < "${#sources[@]}"; i++)); do
url=${sources[$i]}
# Get just the domain from the URL
domain=$(echo "${url}" | cut -d'/' -f3)
# Save the file as list.#.domain
saveLocation=${piholeDir}/list.${i}.${domain}.${justDomainsExtension}
activeDomains[$i]=${saveLocation}
# Save the file as list.#.domain
saveLocation=${piholeDir}/list.${i}.${domain}.${justDomainsExtension}
activeDomains[$i]=${saveLocation}
agent="Mozilla/10.0"
agent="Mozilla/10.0"
echo -n "::: Getting $domain list..."
echo -n "::: Getting ${domain} list..."
# Use a case statement to download lists that need special cURL commands
# to complete properly and reset the user agent when required
case "$domain" in
"adblock.mahakala.is")
agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
cmd_ext="-e http://forum.xda-developers.com/"
;;
# Use a case statement to download lists that need special cURL commands
# to complete properly and reset the user agent when required
case "${domain}" in
"adblock.mahakala.is")
agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
cmd_ext="-e http://forum.xda-developers.com/"
;;
"pgl.yoyo.org")
cmd_ext="-d mimetype=plaintext -d hostformat=hosts"
;;
"pgl.yoyo.org")
cmd_ext="-d mimetype=plaintext -d hostformat=hosts"
;;
# Default is a simple request
*) cmd_ext=""
esac
gravity_transport "$url" "$cmd_ext" "$agent"
# Default is a simple request
*) cmd_ext=""
esac
gravity_transport "${url}" "${cmd_ext}" "${agent}"
done
}
@ -190,9 +189,8 @@ gravity_Schwarzchild() {
# Find all active domains and compile them into one file and remove CRs
echo -n "::: Aggregating list of domains..."
truncate -s 0 ${piholeDir}/${matterAndLight}
for i in "${activeDomains[@]}"
do
cat "$i" | tr -d '\r' >> ${piholeDir}/${matterAndLight}
for i in "${activeDomains[@]}"; do
cat "${i}" | tr -d '\r' >> ${piholeDir}/${matterAndLight}
done
echo " done!"
}
@ -203,8 +201,8 @@ gravity_Blacklist() {
${blacklistScript} -f -nr -q > /dev/null
numBlacklisted=$(wc -l < "/etc/pihole/blacklist.txt")
plural=; [[ "$numBlacklisted" != "1" ]] && plural=s
echo " $numBlacklisted domain${plural} blacklisted!"
plural=; [[ "${numBlacklisted}" != "1" ]] && plural=s
echo " ${numBlacklisted} domain${plural} blacklisted!"
}
gravity_Whitelist() {
@ -214,18 +212,17 @@ gravity_Whitelist() {
echo -n "::: Adding ${#sources[@]} adlist source${plural} to the whitelist..."
urls=()
for url in "${sources[@]}"
do
tmp=$(echo "$url" | awk -F '/' '{print $3}')
urls=("${urls[@]}" ${tmp})
for url in "${sources[@]}"; do
tmp=$(echo "${url}" | awk -F '/' '{print $3}')
urls=("${urls[@]}" ${tmp})
done
echo " done!"
echo -n "::: Running whitelist script to update HOSTS file...."
${whitelistScript} -f -nr -q "${urls[@]}" > /dev/null
numWhitelisted=$(wc -l < "/etc/pihole/whitelist.txt")
plural=; [[ "$numWhitelisted" != "1" ]] && plural=s
echo " $numWhitelisted domain${plural} whitelisted!"
plural=; [[ "${numWhitelisted}" != "1" ]] && plural=s
echo " ${numWhitelisted} domain${plural} whitelisted!"
}
gravity_unique() {
@ -234,7 +231,7 @@ gravity_unique() {
sort -u ${piholeDir}/${supernova} > ${piholeDir}/${eventHorizon}
echo " done!"
numberOf=$(wc -l < ${piholeDir}/${eventHorizon})
echo "::: $numberOf unique domains trapped in the event horizon."
echo "::: ${numberOf} unique domains trapped in the event horizon."
}
gravity_hostFormat() {
@ -248,15 +245,15 @@ gravity_hostFormat() {
echo "::: Error: Unable to determine fully qualified domain name of host"
fi
# If there is a value in the $piholeIPv6, then IPv6 will be used, so the awk command modified to create a line for both protocols
if [[ -n "${IPv6_address}" ]];then
if [[ -n "${IPv6_address}" ]]; then
# Add hostname and dummy domain to the top of gravity.list to make ping result return a friendlier looking domain! Also allows for an easy way to access the Pi-hole admin console (pi.hole/admin)
echo -e "$IPv4addr $hostname\n$IPv6_address $hostname\n$IPv4addr pi.hole\n$IPv6_address pi.hole" > ${piholeDir}/${accretionDisc}
cat ${piholeDir}/${eventHorizon} | awk -v ipv4addr="$IPv4addr" -v ipv6addr="$IPv6_address" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> ${piholeDir}/${accretionDisc}
echo -e "${IPv4addr} ${hostname}\n${IPv6_address} ${hostname}\n${IPv4addr} pi.hole\n${IPv6_address} pi.hole" > ${piholeDir}/${accretionDisc}
cat ${piholeDir}/${eventHorizon} | awk -v ipv4addr="${IPv4addr}" -v ipv6addr="${IPv6_address}" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> ${piholeDir}/${accretionDisc}
else
# Otherwise, just create gravity.list as normal using IPv4
# Add hostname and dummy domain to the top of gravity.list to make ping result return a friendlier looking domain! Also allows for an easy way to access the Pi-hole admin console (pi.hole/admin)
echo -e "$IPv4addr $hostname\n$IPv4addr pi.hole" > ${piholeDir}/${accretionDisc}
cat ${piholeDir}/${eventHorizon} | awk -v ipv4addr="$IPv4addr" '{sub(/\r$/,""); print ipv4addr" "$0}' >> ${piholeDir}/${accretionDisc}
echo -e "${IPv4addr} ${hostname}\n${IPv4addr} pi.hole" > ${piholeDir}/${accretionDisc}
cat ${piholeDir}/${eventHorizon} | awk -v ipv4addr="${IPv4addr}" '{sub(/\r$/,""); print ipv4addr" "$0}' >> ${piholeDir}/${accretionDisc}
fi
# Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it
@ -266,13 +263,12 @@ gravity_hostFormat() {
# blackbody - remove any remnant files from script processes
gravity_blackbody() {
# Loop through list files
for file in ${piholeDir}/*.${justDomainsExtension}
do
for file in ${piholeDir}/*.${justDomainsExtension}; do
# If list is in active array then leave it (noop) else rm the list
if [[ " ${activeDomains[@]} " =~ ${file} ]]; then
:
else
rm -f "$file"
rm -f "${file}"
fi
done
}
@ -290,7 +286,7 @@ gravity_advanced() {
echo " done!"
numberOf=$(wc -l < ${piholeDir}/${supernova})
echo "::: $numberOf domains being pulled in by gravity..."
echo "::: ${numberOf} domains being pulled in by gravity..."
gravity_unique
}
@ -310,35 +306,34 @@ gravity_reload() {
#First escape forward slashes in the path:
adList=${adList//\//\\\/}
#Now replace the line in dnsmasq file
sed -i "s/^addn-hosts.*/addn-hosts=$adList/" /etc/dnsmasq.d/01-pihole.conf
find "$piholeDir" -type f -exec chmod 666 {} \;
sed -i "s/^addn-hosts.*/addn-hosts=${adList}/" /etc/dnsmasq.d/01-pihole.conf
find "${piholeDir}" -type f -exec chmod 666 {} \;
dnsmasqPid=$(pidof dnsmasq)
dnsmasqPid=$(pidof dnsmasq)
if [[ ${dnsmasqPid} ]]; then
# service already running - reload config
if [ -x "$(command -v systemctl)" ]; then
systemctl restart dnsmasq
else
service dnsmasq restart
fi
# service already running - reload config
if [ -x "$(command -v systemctl)" ]; then
systemctl restart dnsmasq
else
service dnsmasq restart
fi
else
# service not running, start it up
if [ -x "$(command -v systemctl)" ]; then
systemctl start dnsmasq
else
service dnsmasq start
fi
# service not running, start it up
if [ -x "$(command -v systemctl)" ]; then
systemctl start dnsmasq
else
service dnsmasq start
fi
fi
}
for var in "$@"
do
case "$var" in
"-f" | "--force" ) forceGrav=true;;
"-h" | "--help" ) helpFunc;;
esac
for var in "$@"; do
case "${var}" in
"-f" | "--force" ) forceGrav=true;;
"-h" | "--help" ) helpFunc;;
esac
done
if [[ ${forceGrav} == true ]]; then

159
pihole
View File

@ -12,130 +12,131 @@
# Must be root to use this tool
if [[ ! $EUID -eq 0 ]];then
if [ -x "$(command -v sudo)" ];then
exec sudo bash "$0" "$@"
exit $?
else
echo "::: sudo is needed to run pihole commands. Please run this script as root or install sudo."
exit 1
fi
if [ -x "$(command -v sudo)" ];then
exec sudo bash "$0" "$@"
exit $?
else
echo "::: sudo is needed to run pihole commands. Please run this script as root or install sudo."
exit 1
fi
fi
whitelistFunc() {
shift
/opt/pihole/whitelist.sh "$@"
exit 0
shift
/opt/pihole/whitelist.sh "$@"
exit 0
}
blacklistFunc() {
shift
/opt/pihole/blacklist.sh "$@"
exit 0
shift
/opt/pihole/blacklist.sh "$@"
exit 0
}
debugFunc() {
/opt/pihole/piholeDebug.sh
exit 0
/opt/pihole/piholeDebug.sh
exit 0
}
flushFunc() {
/opt/pihole/piholeLogFlush.sh
exit 0
/opt/pihole/piholeLogFlush.sh
exit 0
}
updatePiholeFunc() {
/opt/pihole/update.sh
exit 0
/opt/pihole/update.sh
exit 0
}
reconfigurePiholeFunc() {
/etc/.pihole/automated\ install/basic-install.sh --reconfigure
exit 0;
/etc/.pihole/automated\ install/basic-install.sh --reconfigure
exit 0;
}
updateGravityFunc() {
/opt/pihole/gravity.sh "$@"
exit 0
/opt/pihole/gravity.sh "$@"
exit 0
}
setupLCDFunction() {
/opt/pihole/setupLCD.sh
exit 0
/opt/pihole/setupLCD.sh
exit 0
}
queryFunc() {
domain=$2
for list in /etc/pihole/list.*
do
count=$(grep ${domain} $list | wc -l)
echo "::: ${list} (${count} results)"
if [[ ${count} > 0 ]]; then
grep ${domain} ${list}
fi
echo ""
done
exit 0
domain=$2
for list in /etc/pihole/list.*; do
count=$(grep ${domain} $list | wc -l)
echo "::: ${list} (${count} results)"
if [[ ${count} > 0 ]]; then
grep ${domain} ${list}
fi
echo ""
done
exit 0
}
chronometerFunc() {
shift
/opt/pihole/chronometer.sh "$@"
exit 0
shift
/opt/pihole/chronometer.sh "$@"
exit 0
}
uninstallFunc() {
/opt/pihole/uninstall.sh
exit 0
/opt/pihole/uninstall.sh
exit 0
}
versionFunc() {
shift
/opt/pihole/version.sh "$@"
exit 0
shift
/opt/pihole/version.sh "$@"
exit 0
}
helpFunc() {
echo "::: Control all PiHole specific functions!"
echo ":::"
echo "::: Usage: pihole [options]"
echo "::: Add -h after -w (whitelist), -b (blacklist), or -c (chronometer) for more information on usage"
echo ":::"
echo "::: Options:"
echo "::: -w, whitelist Whitelist domains"
echo "::: -b, blacklist Blacklist domains"
echo "::: -d, debug Start a debugging session if having trouble"
echo "::: -f, flush Flush the pihole.log file"
echo "::: -up, updatePihole Update Pi-hole"
echo "::: -g, updateGravity Update the list of ad-serving domains"
echo "::: -s, setupLCD Automatically configures the Pi to use the 2.8 LCD screen to display stats on it"
echo "::: -c, chronometer Calculates stats and displays to an LCD"
echo "::: -h, help Show this help dialog"
echo "::: -v, version Show current versions"
echo "::: -q, query Query the adlists for a specific domain"
echo "::: uninstall Uninstall Pi-Hole from your system :(!"
exit 0
cat << EOM
::: Control all PiHole specific functions!
:::
::: Usage: pihole [options]
::: Add -h after -w (whitelist), -b (blacklist), or -c (chronometer) for more information on usage
:::
::: Options:
::: -w, whitelist Whitelist domains
::: -b, blacklist Blacklist domains
::: -d, debug Start a debugging session if having trouble
::: -f, flush Flush the pihole.log file
::: -up, updatePihole Update Pi-hole
::: -g, updateGravity Update the list of ad-serving domains
::: -s, setupLCD Automatically configures the Pi to use the 2.8 LCD screen to display stats on it
::: -c, chronometer Calculates stats and displays to an LCD
::: -h, help Show this help dialog
::: -v, version Show current versions
::: -q, query Query the adlists for a specific domain
::: uninstall Uninstall Pi-Hole from your system :(!
EOM
exit 1
}
if [[ $# = 0 ]]; then
helpFunc
helpFunc
fi
# Handle redirecting to specific functions based on arguments
case "$1" in
"-w" | "whitelist" ) whitelistFunc "$@";;
"-b" | "blacklist" ) blacklistFunc "$@";;
"-d" | "debug" ) debugFunc;;
"-f" | "flush" ) flushFunc;;
"-up" | "updatePihole" ) updatePiholeFunc;;
"-r" | "reconfigure" ) reconfigurePiholeFunc;;
"-g" | "updateGravity" ) updateGravityFunc "$@";;
"-s" | "setupLCD" ) setupLCDFunction;;
"-c" | "chronometer" ) chronometerFunc "$@";;
"-h" | "help" ) helpFunc;;
"-v" | "version" ) versionFunc "$@";;
"-q" | "query" ) queryFunc "$@";;
"uninstall" ) uninstallFunc;;
* ) helpFunc;;
case "${1}" in
"-w" | "whitelist" ) whitelistFunc "$@";;
"-b" | "blacklist" ) blacklistFunc "$@";;
"-d" | "debug" ) debugFunc;;
"-f" | "flush" ) flushFunc;;
"-up" | "updatePihole" ) updatePiholeFunc;;
"-r" | "reconfigure" ) reconfigurePiholeFunc;;
"-g" | "updateGravity" ) updateGravityFunc "$@";;
"-s" | "setupLCD" ) setupLCDFunction;;
"-c" | "chronometer" ) chronometerFunc "$@";;
"-h" | "help" ) helpFunc;;
"-v" | "version" ) versionFunc "$@";;
"-q" | "query" ) queryFunc "$@";;
"uninstall" ) uninstallFunc;;
* ) helpFunc;;
esac