Colourise Core Output Text (#1471)

* Define colours within COL_TABLE
* Do not output colours for non-terminal instances
* Removed ":::"
* Fixed indenting & spacing
* Made output consistent throughout project
* Reworded text to fit on standard 80 char wide Terminal screen
* Made 'sudo raspi-config' warning (insufficient disk space) only show on RPi
* Make "Installation/Update Complete" the final msg
* Remove redundant messages
* Simplify update available message
* Confirm user would like to begin uninstall
* If "git pull" string says "Already up-to-date.", place [i] before it
* Colour Temp/Interface output
* Made `pihole disable 5z` invalid
* Added error fallback if invalid argument (not s/m) is detected
* Quoted "$2" for consistency
* Updated help text
* L185/286: Replaced echo with redirect
* User agents for adblock.mahakala.is/adaway.org unnecessary 
* Print newline on confirmation of repository reset
* Add output to admin-related dnsmasq restarts
* Return error message for "pihole -q"
* Imply default checkout behaviour with y/N
* Fix uninstall failing to remove pihole user
* Print checkout 'git remote show origin' STDERR on new line
* Replaced checkout "AdminLTE" wording with "Web Admin"
pull/1561/head
Adam Warner 7 years ago committed by WaLLy3K
parent 6f2ec22894
commit 536585b846

@ -0,0 +1,28 @@
if [[ -t 1 ]] && [[ $(tput colors) -ge 8 ]]; then
COL_NC=''
COL_WHITE=''
COL_BLACK=''
COL_BLUE=''
COL_LIGHT_BLUE=''
COL_GREEN=''
COL_LIGHT_GREEN=''
COL_CYAN=''
COL_LIGHT_CYAN=''
COL_RED=''
COL_LIGHT_RED=''
COL_URG_RED=''
COL_PURPLE=''
COL_LIGHT_PURPLE=''
COL_BROWN=''
COL_YELLOW=''
COL_GRAY=''
COL_LIGHT_GRAY=''
COL_DARK_GRAY=''
fi
TICK="[${COL_LIGHT_GREEN}✓${COL_NC}]"
CROSS="[${COL_LIGHT_RED}✗${COL_NC}]"
INFO="[i]"
QST="[?]"
DONE="${COL_LIGHT_GREEN} done!${COL_NC}"
OVER="\r\033[K"

@ -24,6 +24,10 @@ domToRemoveList=()
listMain="" listMain=""
listAlt="" listAlt=""
colfile="/opt/pihole/COL_TABLE"
source ${colfile}
helpFunc() { helpFunc() {
if [[ "${listMain}" == "${whitelist}" ]]; then if [[ "${listMain}" == "${whitelist}" ]]; then
param="w" param="w"
@ -64,8 +68,9 @@ HandleOther() {
# Check validity of domain # Check validity of domain
validDomain=$(echo "${domain}" | perl -lne 'print if /(?!.*[^a-z0-9-\.].*)^((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9-]+\.)*[a-z]{2,63}/') validDomain=$(echo "${domain}" | perl -lne 'print if /(?!.*[^a-z0-9-\.].*)^((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9-]+\.)*[a-z]{2,63}/')
if [[ -z "${validDomain}" ]]; then if [[ -z "${validDomain}" ]]; then
echo "::: $1 is not a valid argument or domain name" echo -e " ${CROSS} $1 is not a valid argument or domain name!"
else else
echo -e " ${TICK} $1 is a valid domain name!"
domList=("${domList[@]}" ${validDomain}) domList=("${domList[@]}" ${validDomain})
fi fi
} }
@ -93,6 +98,10 @@ PoplistFile() {
AddDomain() { AddDomain() {
list="$2" list="$2"
domain=$(EscapeRegexp "$1") domain=$(EscapeRegexp "$1")
[[ "${list}" == "${whitelist}" ]] && listname="whitelist"
[[ "${list}" == "${blacklist}" ]] && listname="blacklist"
[[ "${list}" == "${wildcardlist}" ]] && listname="wildcard blacklist"
if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then
bool=true bool=true
@ -102,14 +111,14 @@ AddDomain() {
if [[ "${bool}" == false ]]; then if [[ "${bool}" == false ]]; then
# Domain not found in the whitelist file, add it! # Domain not found in the whitelist file, add it!
if [[ "${verbose}" == true ]]; then if [[ "${verbose}" == true ]]; then
echo "::: Adding $1 to $list..." echo -e " ${INFO} Adding $1 to $listname..."
fi fi
reload=true reload=true
# Add it to the list we want to add it to # Add it to the list we want to add it to
echo "$1" >> "${list}" echo "$1" >> "${list}"
else else
if [[ "${verbose}" == true ]]; then if [[ "${verbose}" == true ]]; then
echo "::: ${1} already exists in ${list}, no need to add!" echo -e " ${INFO} ${1} already exists in ${listname}, no need to add!"
fi fi
fi fi
elif [[ "${list}" == "${wildcardlist}" ]]; then elif [[ "${list}" == "${wildcardlist}" ]]; then
@ -124,7 +133,7 @@ AddDomain() {
if [[ "${bool}" == false ]]; then if [[ "${bool}" == false ]]; then
if [[ "${verbose}" == true ]]; then if [[ "${verbose}" == true ]]; then
echo "::: Adding $1 to wildcard blacklist..." echo -e " ${INFO} Adding $1 to wildcard blacklist..."
fi fi
reload=true reload=true
echo "address=/$1/${IPV4_ADDRESS}" >> "${wildcardlist}" echo "address=/$1/${IPV4_ADDRESS}" >> "${wildcardlist}"
@ -133,67 +142,78 @@ AddDomain() {
fi fi
else else
if [[ "${verbose}" == true ]]; then if [[ "${verbose}" == true ]]; then
echo "::: ${1} already exists in wildcard blacklist, no need to add!" echo -e " ${INFO} ${1} already exists in wildcard blacklist, no need to add!"
fi fi
fi fi
fi fi
} }
RemoveDomain() { RemoveDomain() {
list="$2" list="$2"
domain=$(EscapeRegexp "$1") domain=$(EscapeRegexp "$1")
if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then [[ "${list}" == "${whitelist}" ]] && listname="whitelist"
bool=true [[ "${list}" == "${blacklist}" ]] && listname="blacklist"
# Is it in the list? Logic follows that if its whitelisted it should not be blacklisted and vice versa [[ "${list}" == "${wildcardlist}" ]] && listname="wildcard blacklist"
grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false
if [[ "${bool}" == true ]]; then if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then
# Remove it from the other one bool=true
echo "::: Removing $1 from $list..." # Is it in the list? Logic follows that if its whitelisted it should not be blacklisted and vice versa
# /I flag: search case-insensitive grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false
sed -i "/${domain}/Id" "${list}" if [[ "${bool}" == true ]]; then
reload=true # Remove it from the other one
else echo -e " ${INFO} Removing $1 from $listname..."
if [[ "${verbose}" == true ]]; then # /I flag: search case-insensitive
echo "::: ${1} does not exist in ${list}, no need to remove!" sed -i "/${domain}/Id" "${list}"
fi reload=true
else
if [[ "${verbose}" == true ]]; then
echo -e " ${INFO} ${1} does not exist in ${listname}, no need to remove!"
fi fi
elif [[ "${list}" == "${wildcardlist}" ]]; then fi
bool=true elif [[ "${list}" == "${wildcardlist}" ]]; then
# Is it in the list? bool=true
grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false # Is it in the list?
if [[ "${bool}" == true ]]; then grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false
# Remove it from the other one if [[ "${bool}" == true ]]; then
echo "::: Removing $1 from $list..." # Remove it from the other one
# /I flag: search case-insensitive echo -e " ${INFO} Removing $1 from $listname..."
sed -i "/address=\/${domain}/Id" "${list}" # /I flag: search case-insensitive
reload=true sed -i "/address=\/${domain}/Id" "${list}"
else reload=true
if [[ "${verbose}" == true ]]; then else
echo "::: ${1} does not exist in ${list}, no need to remove!" if [[ "${verbose}" == true ]]; then
fi echo -e " ${INFO} ${1} does not exist in ${listname}, no need to remove!"
fi fi
fi fi
fi
} }
Reload() { Reload() {
# Reload hosts file # Reload hosts file
echo ""
echo -e " ${INFO} Updating gravity..."
echo ""
pihole -g -sd pihole -g -sd
} }
Displaylist() { Displaylist() {
if [[ "${listMain}" == "${whitelist}" ]]; then if [[ -f ${listMain} ]]; then
string="gravity resistant domains" if [[ "${listMain}" == "${whitelist}" ]]; then
string="gravity resistant domains"
else
string="domains caught in the sinkhole"
fi
verbose=false
echo -e "Displaying $string:\n"
count=1
while IFS= read -r RD; do
echo " ${count}: ${RD}"
count=$((count+1))
done < "${listMain}"
else else
string="domains caught in the sinkhole" echo -e " ${COL_LIGHT_RED}${listMain} does not exist!${COL_NC}"
fi fi
verbose=false
echo -e "Displaying $string:\n"
count=1
while IFS= read -r RD; do
echo "${count}: ${RD}"
count=$((count+1))
done < "${listMain}"
exit 0; exit 0;
} }

@ -9,7 +9,8 @@
# Please see LICENSE file for your rights under this license. # Please see LICENSE file for your rights under this license.
readonly PI_HOLE_FILES_DIR="/etc/.pihole" readonly PI_HOLE_FILES_DIR="/etc/.pihole"
PH_TEST="true" source "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh" PH_TEST="true"
source "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh"
# webInterfaceGitUrl set in basic-install.sh # webInterfaceGitUrl set in basic-install.sh
# webInterfaceDir set in basic-install.sh # webInterfaceDir set in basic-install.sh
@ -20,9 +21,8 @@ PH_TEST="true" source "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh"
source "${setupVars}" source "${setupVars}"
update="false" update="false"
# Colour codes coltable="/opt/pihole/COL_TABLE"
red="\e[1;31m" source ${coltable}
def="\e[0m"
fully_fetch_repo() { fully_fetch_repo() {
# Add upstream branches to shallow clone # Add upstream branches to shallow clone
@ -41,10 +41,12 @@ fully_fetch_repo() {
get_available_branches() { get_available_branches() {
# Return available branches # Return available branches
local directory="${1}" local directory="${1}"
local output
cd "${directory}" || return 1 cd "${directory}" || return 1
# Get reachable remote branches # Get reachable remote branches, but store STDERR as STDOUT variable
git remote show origin | grep 'tracked' | sed 's/tracked//;s/ //g' output=$( { git remote show origin | grep 'tracked' | sed 's/tracked//;s/ //g'; } 2>&1 )
echo "$output"
return return
} }
@ -72,29 +74,36 @@ checkout_pull_branch() {
cd "${directory}" || return 1 cd "${directory}" || return 1
oldbranch="$(git symbolic-ref HEAD)" oldbranch="$(git symbolic-ref HEAD)"
git checkout "${branch}" || return 1 git checkout "${branch}" || return 1
if [ "$(git diff "${oldbranch}" | grep -c "^")" -gt "0" ]; then if [[ "$(git diff "${oldbranch}" | grep -c "^")" -gt "0" ]]; then
update="true" update="true"
fi fi
git pull || return 1 git_pull=$(git pull || return 1)
if [[ "$git_pull" == *"up-to-date"* ]]; then
echo -e "\n ${INFO} $(git pull)"
else
echo -e "$git_pull\n"
fi
return 0 return 0
} }
warning1() { warning1() {
echo " Please note that changing branches severely alters your Pi-hole subsystems" echo " Please note that changing branches severely alters your Pi-hole subsystems"
echo " Features that work on the master branch, may not on a development branch" echo " Features that work on the master branch, may not on a development branch"
echo -e " ${red}This feature is NOT supported unless a Pi-hole developer explicitly asks!${def}" echo -e " ${COL_LIGHT_RED}This feature is NOT supported unless a Pi-hole developer explicitly asks!${COL_NC}"
read -r -p " Have you read and understood this? [y/N] " response read -r -p " Have you read and understood this? [y/N] " response
case ${response} in case ${response} in
[yY][eE][sS]|[yY]) [yY][eE][sS]|[yY])
echo "::: Continuing with branch change." echo ""
return 0 return 0
;; ;;
*) *)
echo "::: Branch change has been cancelled." echo -e "\n ${INFO} Branch change has been cancelled"
return 1 return 1
;; ;;
esac esac
@ -107,24 +116,23 @@ checkout() {
# Avoid globbing # Avoid globbing
set -f set -f
#This is unlikely # This is unlikely
if ! is_repo "${PI_HOLE_FILES_DIR}" ; then if ! is_repo "${PI_HOLE_FILES_DIR}" ; then
echo "::: Critical Error: Core Pi-hole repo is missing from system!" echo -e " ${COL_LIGHT_RED}Error: Core Pi-hole repo is missing from system!
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole" Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}"
exit 1; exit 1;
fi fi
if [[ ${INSTALL_WEB} == "true" ]]; then if [[ ${INSTALL_WEB} == "true" ]]; then
if ! is_repo "${webInterfaceDir}" ; then if ! is_repo "${webInterfaceDir}" ; then
echo "::: Critical Error: Web Admin repo is missing from system!" echo -e " ${COL_LIGHT_RED}Error: Web Admin repo is missing from system!
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole" Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}"
exit 1; exit 1;
fi fi
fi fi
if [[ -z "${1}" ]]; then if [[ -z "${1}" ]]; then
echo "::: No option detected. Please use 'pihole checkout <master|dev>'." echo -e " ${COL_LIGHT_RED}Invalid option${COL_NC}
echo "::: Or enter the repository and branch you would like to check out:" Try 'pihole checkout --help' for more information."
echo "::: 'pihole checkout <web|core> <branchname>'"
exit 1 exit 1
fi fi
@ -134,72 +142,91 @@ checkout() {
if [[ "${1}" == "dev" ]] ; then if [[ "${1}" == "dev" ]] ; then
# Shortcut to check out development branches # Shortcut to check out development branches
echo "::: Shortcut \"dev\" detected - checking out development / devel branches ..." echo -e " ${INFO} Shortcut \"dev\" detected - checking out development / devel branches..."
echo "::: Pi-hole core" echo -e " ${INFO} Pi-hole core"
fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "development" || { echo "Unable to pull Core developement branch"; exit 1; } fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "development" || { echo " ${CROSS} Unable to pull Core developement branch"; exit 1; }
if [[ ${INSTALL_WEB} == "true" ]]; then if [[ ${INSTALL_WEB} == "true" ]]; then
echo "::: Web interface" echo -e " ${INFO} Web interface"
fetch_checkout_pull_branch "${webInterfaceDir}" "devel" || { echo "Unable to pull Web development branch"; exit 1; } fetch_checkout_pull_branch "${webInterfaceDir}" "devel" || { echo " ${CROSS} Unable to pull Web development branch"; exit 1; }
fi fi
echo "::: done!" echo -e " ${TICK} Pi-hole core"
elif [[ "${1}" == "master" ]] ; then elif [[ "${1}" == "master" ]] ; then
# Shortcut to check out master branches # Shortcut to check out master branches
echo "::: Shortcut \"master\" detected - checking out master branches ..." echo -e " ${INFO} Shortcut \"master\" detected - checking out master branches..."
echo "::: Pi-hole core" echo -e " ${INFO} Pi-hole core"
fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "master" || { echo "Unable to pull Core master branch"; exit 1; } fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "master" || { echo " ${CROSS} Unable to pull Core master branch"; exit 1; }
if [[ ${INSTALL_WEB} == "true" ]]; then if [[ ${INSTALL_WEB} == "true" ]]; then
echo "::: Web interface" echo -e " ${INFO} Web interface"
fetch_checkout_pull_branch "${webInterfaceDir}" "master" || { echo "Unable to pull web master branch"; exit 1; } fetch_checkout_pull_branch "${webInterfaceDir}" "master" || { echo " ${CROSS} Unable to pull Web master branch"; exit 1; }
fi fi
echo "::: done!" echo -e " ${TICK} Web interface"
elif [[ "${1}" == "core" ]] ; then elif [[ "${1}" == "core" ]] ; then
echo -n "::: Fetching remote branches for Pi-hole core from ${piholeGitUrl} ... " str="Fetching branches from ${piholeGitUrl}"
echo -ne " ${INFO} $str"
if ! fully_fetch_repo "${PI_HOLE_FILES_DIR}" ; then if ! fully_fetch_repo "${PI_HOLE_FILES_DIR}" ; then
echo "::: Fetching all branches for Pi-hole core repo failed!" echo -e " ${CROSS} $str"
exit 1 exit 1
fi fi
corebranches=($(get_available_branches "${PI_HOLE_FILES_DIR}")) corebranches=($(get_available_branches "${PI_HOLE_FILES_DIR}"))
echo " done!"
echo "::: ${#corebranches[@]} branches available" if [[ "${corebranches[@]}" == *"master"* ]]; then
echo ":::" echo -e "${OVER} ${TICK} $str
# Have to user chosing the branch he wants ${INFO} ${#corebranches[@]} branches available for Pi-hole Core"
else
# Print STDERR output from get_available_branches
echo -e "${OVER} ${CROSS} $str\n\n${corebranches[*]}"
exit 1
fi
echo ""
# Have the user choose the branch they want
if ! (for e in "${corebranches[@]}"; do [[ "$e" == "${2}" ]] && exit 0; done); then if ! (for e in "${corebranches[@]}"; do [[ "$e" == "${2}" ]] && exit 0; done); then
echo "::: Requested branch \"${2}\" is not available!" echo -e " ${INFO} Requested branch \"${2}\" is not available"
echo "::: Available branches for core are:" echo -e " ${INFO} Available branches for Core are:"
for e in "${corebranches[@]}"; do echo "::: $e"; done for e in "${corebranches[@]}"; do echo " - $e"; done
exit 1 exit 1
fi fi
checkout_pull_branch "${PI_HOLE_FILES_DIR}" "${2}" checkout_pull_branch "${PI_HOLE_FILES_DIR}" "${2}"
elif [[ "${1}" == "web" && "${INSTALL_WEB}" == "true" ]] ; then elif [[ "${1}" == "web" ]] && [[ "${INSTALL_WEB}" == "true" ]] ; then
echo -n "::: Fetching remote branches for the web interface from ${webInterfaceGitUrl} ... " str="Fetching branches from ${webInterfaceGitUrl}"
echo -ne " ${INFO} $str"
if ! fully_fetch_repo "${webInterfaceDir}" ; then if ! fully_fetch_repo "${webInterfaceDir}" ; then
echo "::: Fetching all branches for Pi-hole web interface repo failed!" echo -e " ${CROSS} $str"
exit 1 exit 1
fi fi
webbranches=($(get_available_branches "${webInterfaceDir}")) webbranches=($(get_available_branches "${webInterfaceDir}"))
echo " done!"
echo "::: ${#webbranches[@]} branches available" if [[ "${corebranches[@]}" == *"master"* ]]; then
echo ":::" echo -e "${OVER} ${TICK} $str
# Have to user chosing the branch he wants ${INFO} ${#webbranches[@]} branches available for Web Admin"
else
# Print STDERR output from get_available_branches
echo -e "${OVER} ${CROSS} $str\n\n${corebranches[*]}"
exit 1
fi
echo ""
# Have the user choose the branch they want
if ! (for e in "${webbranches[@]}"; do [[ "$e" == "${2}" ]] && exit 0; done); then if ! (for e in "${webbranches[@]}"; do [[ "$e" == "${2}" ]] && exit 0; done); then
echo "::: Requested branch \"${2}\" is not available!" echo -e " ${INFO} Requested branch \"${2}\" is not available"
echo "::: Available branches for web are:" echo -e " ${INFO} Available branches for Web Admin are:"
for e in "${webbranches[@]}"; do echo "::: $e"; done for e in "${webbranches[@]}"; do echo " - $e"; done
exit 1 exit 1
fi fi
checkout_pull_branch "${webInterfaceDir}" "${2}" checkout_pull_branch "${webInterfaceDir}" "${2}"
else else
echo "::: Requested option \"${1}\" is not available!" echo -e " ${INFO} Requested option \"${1}\" is not available"
exit 1 exit 1
fi fi
# Force updating everything # Force updating everything
if [[ ! "${1}" == "web" && "${update}" == "true" ]]; then if [[ ! "${1}" == "web" && "${update}" == "true" ]]; then
echo "::: Running installer to upgrade your installation" echo -e " ${INFO} Running installer to upgrade your installation"
if "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh" --unattended; then if "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh" --unattended; then
exit 0 exit 0
else else
echo "Unable to complete update, contact Pi-hole" echo -e " ${COL_LIGHT_RED} Error: Unable to complete update, please contact support${COL_NC}"
exit 1 exit 1
fi fi
fi fi

@ -8,8 +8,11 @@
# This file is copyright under the latest version of the EUPL. # This file is copyright under the latest version of the EUPL.
# Please see LICENSE file for your rights under this license. # Please see LICENSE file for your rights under this license.
colfile="/opt/pihole/COL_TABLE"
source ${colfile}
if [[ "$@" != *"quiet"* ]]; then if [[ "$@" != *"quiet"* ]]; then
echo -n "::: Flushing /var/log/pihole.log ..." echo -ne " ${INFO} Flushing /var/log/pihole.log ..."
fi fi
if [[ "$@" == *"once"* ]]; then if [[ "$@" == *"once"* ]]; then
# Nightly logrotation # Nightly logrotation
@ -41,5 +44,5 @@ else
fi fi
if [[ "$@" != *"quiet"* ]]; then if [[ "$@" != *"quiet"* ]]; then
echo "... done!" echo -e "${OVER} ${TICK} Flushed /var/log/pihole.log"
fi fi

@ -22,6 +22,10 @@ readonly PI_HOLE_FILES_DIR="/etc/.pihole"
PH_TEST=true PH_TEST=true
source ${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh source ${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh
colfile="/opt/pihole/COL_TABLE"
source ${colfile}
# is_repo() sourced from basic-install.sh # is_repo() sourced from basic-install.sh
# make_repo() sourced from basic-install.sh # make_repo() sourced from basic-install.sh
# update_repo() source from basic-install.sh # update_repo() source from basic-install.sh
@ -49,14 +53,14 @@ GitCheckUpdateAvail() {
REMOTE="$(git rev-parse @{upstream})" REMOTE="$(git rev-parse @{upstream})"
if [[ ${#LOCAL} == 0 ]]; then if [[ ${#LOCAL} == 0 ]]; then
echo "::: Error: Local revision could not be obtained, ask Pi-hole support." echo -e " ${COL_LIGHT_RED}Error: Local revision could not be obtained, ask Pi-hole support."
echo "::: Additional debugging output:" echo -e " Additional debugging output:${COL_NC}"
git status git status
exit exit
fi fi
if [[ ${#REMOTE} == 0 ]]; then if [[ ${#REMOTE} == 0 ]]; then
echo "::: Error: Remote revision could not be obtained, ask Pi-hole support." echo -e " ${COL_LIGHT_RED}Error: Remote revision could not be obtained, ask Pi-hole support."
echo "::: Additional debugging output:" echo -e " Additional debugging output:${COL_NC}"
git status git status
exit exit
fi fi
@ -94,52 +98,52 @@ main() {
#This is unlikely #This is unlikely
if ! is_repo "${PI_HOLE_FILES_DIR}" ; then if ! is_repo "${PI_HOLE_FILES_DIR}" ; then
echo "::: Critical Error: Core Pi-hole repo is missing from system!" echo -e " ${COL_LIGHT_RED}Critical Error: Core Pi-hole repo is missing from system!"
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole" echo -e " Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}"
exit 1; exit 1;
fi fi
echo "::: Checking for updates..." echo -e " ${INFO} Checking for updates..."
if GitCheckUpdateAvail "${PI_HOLE_FILES_DIR}" ; then if GitCheckUpdateAvail "${PI_HOLE_FILES_DIR}" ; then
core_update=true core_update=true
echo "::: Pi-hole Core: update available" echo -e " ${INFO} Pi-hole Core:\t${COL_YELLOW}update available${COL_NC}"
else else
core_update=false core_update=false
echo "::: Pi-hole Core: up to date" echo -e " ${INFO} Pi-hole Core:\t${COL_LIGHT_GREEN}up to date${COL_NC}"
fi fi
if FTLcheckUpdate ; then if FTLcheckUpdate ; then
FTL_update=true FTL_update=true
echo "::: FTL: update available" echo -e " ${INFO} FTL:\t\t${COL_YELLOW}update available${COL_NC}"
else else
FTL_update=false FTL_update=false
echo "::: FTL: up to date" echo -e " ${INFO} FTL:\t\t${COL_LIGHT_GREEN}up to date${COL_NC}"
fi fi
# Logic: Don't update FTL when there is a core update available # Logic: Don't update FTL when there is a core update available
# since the core update will run the installer which will itself # since the core update will run the installer which will itself
# re-install (i.e. update) FTL # re-install (i.e. update) FTL
if ${FTL_update} && ! ${core_update}; then if ${FTL_update} && ! ${core_update}; then
echo ":::" echo ""
echo "::: FTL out of date" echo -e " ${INFO} FTL out of date"
FTLdetect FTLdetect
echo ":::" echo ""
fi fi
if [[ ${INSTALL_WEB} == true ]]; then if [[ ${INSTALL_WEB} == true ]]; then
if ! is_repo "${ADMIN_INTERFACE_DIR}" ; then if ! is_repo "${ADMIN_INTERFACE_DIR}" ; then
echo "::: Critical Error: Web Admin repo is missing from system!" echo -e " ${COL_LIGHT_RED}Critical Error: Web Admin repo is missing from system!"
echo "::: Please re-run install script from https://github.com/pi-hole/pi-hole" echo -e " Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}"
exit 1; exit 1;
fi fi
if GitCheckUpdateAvail "${ADMIN_INTERFACE_DIR}" ; then if GitCheckUpdateAvail "${ADMIN_INTERFACE_DIR}" ; then
web_update=true web_update=true
echo "::: Web Interface: update available" echo -e " ${INFO} Web Interface:\t${COL_YELLOW}update available${COL_NC}"
else else
web_update=false web_update=false
echo "::: Web Interface: up to date" echo -e " ${INFO} Web Interface:\t${COL_LIGHT_GREEN}up to date${COL_NC}"
fi fi
# Logic # Logic
@ -154,64 +158,64 @@ main() {
if ! ${core_update} && ! ${web_update} ; then if ! ${core_update} && ! ${web_update} ; then
if ! ${FTL_update} ; then if ! ${FTL_update} ; then
echo ":::" echo ""
echo "::: Everything is up to date!" echo -e " ${TICK} Everything is up to date!"
exit 0 exit 0
fi fi
elif ! ${core_update} && ${web_update} ; then elif ! ${core_update} && ${web_update} ; then
echo ":::" echo ""
echo "::: Pi-hole Web Admin files out of date" echo -e " ${INFO} Pi-hole Web Admin files out of date"
getGitFiles "${ADMIN_INTERFACE_DIR}" "${ADMIN_INTERFACE_GIT_URL}" getGitFiles "${ADMIN_INTERFACE_DIR}" "${ADMIN_INTERFACE_GIT_URL}"
elif ${core_update} && ! ${web_update} ; then elif ${core_update} && ! ${web_update} ; then
echo ":::" echo ""
echo "::: Pi-hole core files out of date" echo -e " ${INFO} Pi-hole core files out of date"
getGitFiles "${PI_HOLE_FILES_DIR}" "${PI_HOLE_GIT_URL}" getGitFiles "${PI_HOLE_FILES_DIR}" "${PI_HOLE_GIT_URL}"
${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh --reconfigure --unattended || echo "Unable to complete update, contact Pi-hole" && exit 1 ${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh --reconfigure --unattended || echo -e " ${COL_LIGHT_RED}Unable to complete update, contact Pi-hole${COL_NC}" && exit 1
elif ${core_update} && ${web_update} ; then elif ${core_update} && ${web_update} ; then
echo ":::" echo ""
echo "::: Updating Pi-hole core and web admin files" echo -e " ${INFO} Updating Pi-hole core and web admin files"
getGitFiles "${PI_HOLE_FILES_DIR}" "${PI_HOLE_GIT_URL}" getGitFiles "${PI_HOLE_FILES_DIR}" "${PI_HOLE_GIT_URL}"
${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh --unattended || echo "Unable to complete update, contact Pi-hole" && exit 1 ${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh --unattended || echo -e " ${COL_LIGHT_RED}Unable to complete update, contact Pi-hole${COL_NC}" && exit 1
else else
echo "*** Update script has malfunctioned, fallthrough reached. Please contact support" echo -e " ${COL_LIGHT_RED}Update script has malfunctioned, fallthrough reached. Please contact support${COL_NC}"
exit 1 exit 1
fi fi
else # Web Admin not installed, so only verify if core is up to date else # Web Admin not installed, so only verify if core is up to date
if ! ${core_update}; then if ! ${core_update}; then
if ! ${FTL_update} ; then if ! ${FTL_update} ; then
echo ":::" echo ""
echo "::: Everything is up to date!" echo -e " ${INFO} Everything is up to date!"
exit 0 exit 0
fi fi
else else
echo ":::" echo ""
echo "::: Pi-hole core files out of date" echo -e " ${INFO} Pi-hole core files out of date"
getGitFiles "${PI_HOLE_FILES_DIR}" "${PI_HOLE_GIT_URL}" getGitFiles "${PI_HOLE_FILES_DIR}" "${PI_HOLE_GIT_URL}"
${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh --reconfigure --unattended || echo "Unable to complete update, contact Pi-hole" && exit 1 ${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh --reconfigure --unattended || echo -e " ${COL_LIGHT_RED}Unable to complete update, contact Pi-hole${COL_NC}" && exit 1
fi fi
fi fi
if [[ "${web_update}" == true ]]; then if [[ "${web_update}" == true ]]; then
web_version_current="$(/usr/local/bin/pihole version --admin --current)" web_version_current="$(/usr/local/bin/pihole version --admin --current)"
echo ":::" echo ""
echo "::: Web Admin version is now at ${web_version_current/* v/v}}" echo -e " ${INFO} Web Admin version is now at ${web_version_current/* v/v}"
echo "::: If you had made any changes in '/var/www/html/admin/', they have been stashed using 'git stash'" echo -e " ${INFO} If you had made any changes in '/var/www/html/admin/', they have been stashed using 'git stash'"
fi fi
if [[ "${core_update}" == true ]]; then if [[ "${core_update}" == true ]]; then
pihole_version_current="$(/usr/local/bin/pihole version --pihole --current)" pihole_version_current="$(/usr/local/bin/pihole version --pihole --current)"
echo ":::" echo ""
echo "::: Pi-hole version is now at ${pihole_version_current/* v/v}}" echo -e " ${INFO} Pi-hole version is now at ${pihole_version_current/* v/v}"
echo "::: If you had made any changes in '/etc/.pihole/', they have been stashed using 'git stash'" echo -e " ${INFO} If you had made any changes in '/etc/.pihole/', they have been stashed using 'git stash'"
fi fi
if [[ ${FTL_update} == true ]]; then if [[ ${FTL_update} == true ]]; then
FTL_version_current="$(/usr/local/bin/pihole version --ftl --current)" FTL_version_current="$(/usr/bin/pihole-FTL tag)"
echo ":::" echo ""
echo "::: FTL version is now at ${FTL_version_current/* v/v}}" echo -e " ${INFO} FTL version is now at ${FTL_version_current/* v/v}"
start_service pihole-FTL start_service pihole-FTL
enable_service pihole-FTL enable_service pihole-FTL
fi fi

@ -14,13 +14,17 @@ readonly dhcpconfig="/etc/dnsmasq.d/02-pihole-dhcp.conf"
# 03 -> wildcards # 03 -> wildcards
readonly dhcpstaticconfig="/etc/dnsmasq.d/04-pihole-static-dhcp.conf" readonly dhcpstaticconfig="/etc/dnsmasq.d/04-pihole-static-dhcp.conf"
coltable="/opt/pihole/COL_TABLE"
if [[ -f ${coltable} ]]; then
source ${coltable}
fi
helpFunc() { helpFunc() {
echo "Usage: pihole -a [options] echo "Usage: pihole -a [options]
Example: pihole -a -p password Example: pihole -a -p password
Set options for the Admin Console Set options for the Admin Console
Options: Options:
-f, flush Flush the Pi-hole log
-p, password Set Admin Console password -p, password Set Admin Console password
-c, celsius Set Celsius as preferred temperature unit -c, celsius Set Celsius as preferred temperature unit
-f, fahrenheit Set Fahrenheit as preferred temperature unit -f, fahrenheit Set Fahrenheit as preferred temperature unit
@ -58,6 +62,7 @@ delete_dnsmasq_setting() {
SetTemperatureUnit() { SetTemperatureUnit() {
change_setting "TEMPERATUREUNIT" "${unit}" change_setting "TEMPERATUREUNIT" "${unit}"
echo -e " ${TICK} Set temperature unit to ${unit}"
} }
HashPassword() { HashPassword() {
@ -89,7 +94,7 @@ SetWebPassword() {
if [ "${PASSWORD}" == "" ]; then if [ "${PASSWORD}" == "" ]; then
change_setting "WEBPASSWORD" "" change_setting "WEBPASSWORD" ""
echo "Password Removed" echo -e " ${TICK} Password Removed"
exit 0 exit 0
fi fi
@ -101,9 +106,9 @@ SetWebPassword() {
hash=$(HashPassword ${PASSWORD}) hash=$(HashPassword ${PASSWORD})
# Save hash to file # Save hash to file
change_setting "WEBPASSWORD" "${hash}" change_setting "WEBPASSWORD" "${hash}"
echo "New password set" echo -e " ${TICK} New password set"
else else
echo "Passwords don't match. Your password has not been changed" echo -e " ${CROSS} Passwords don't match. Your password has not been changed"
exit 1 exit 1
fi fi
} }
@ -213,11 +218,19 @@ Reboot() {
} }
RestartDNS() { RestartDNS() {
if [ -x "$(command -v systemctl)" ]; then local str="Restarting dnsmasq"
systemctl restart dnsmasq &> /dev/null echo -ne " ${INFO} ${str}..."
else if [[ -x "$(command -v systemctl)" ]]; then
service dnsmasq restart &> /dev/null systemctl restart dnsmasq
fi else
service dnsmasq restart
fi
if [[ "$?" == 0 ]]; then
echo -e "${OVER} ${TICK} ${str}"
else
echo -e "${OVER} ${CROSS} ${str}"
fi
} }
SetQueryLogOptions() { SetQueryLogOptions() {
@ -404,13 +417,13 @@ Interfaces:
fi fi
if [[ "${args[2]}" == "all" ]]; then if [[ "${args[2]}" == "all" ]]; then
echo "Listening on all interfaces, permiting all origins, hope you have a firewall!" echo -e " ${INFO} Listening on all interfaces, permiting all origins. Please use a firewall!"
change_setting "DNSMASQ_LISTENING" "all" change_setting "DNSMASQ_LISTENING" "all"
elif [[ "${args[2]}" == "local" ]]; then elif [[ "${args[2]}" == "local" ]]; then
echo "Listening on all interfaces, permitting only origins that are at most one hop away (local devices)" echo -e " ${INFO} Listening on all interfaces, permiting origins from one hop away (LAN)"
change_setting "DNSMASQ_LISTENING" "local" change_setting "DNSMASQ_LISTENING" "local"
else else
echo "Listening only on interface ${PIHOLE_INTERFACE}" echo -e " ${INFO} Listening only on interface ${PIHOLE_INTERFACE}"
change_setting "DNSMASQ_LISTENING" "single" change_setting "DNSMASQ_LISTENING" "single"
fi fi

File diff suppressed because it is too large Load Diff

@ -8,19 +8,30 @@
# This file is copyright under the latest version of the EUPL. # This file is copyright under the latest version of the EUPL.
# Please see LICENSE file for your rights under this license. # Please see LICENSE file for your rights under this license.
source "/opt/pihole/COL_TABLE"
while true; do
read -rp " ${QST} Are you sure you would like to remove ${COL_WHITE}Pi-hole${COL_NC}? [y/N] " yn
case ${yn} in
[Yy]* ) break;;
[Nn]* ) echo -e "\n ${COL_LIGHT_GREEN}Uninstall has been cancelled${COL_NC}"; exit 0;;
* ) echo -e "\n ${COL_LIGHT_GREEN}Uninstall has been cancelled${COL_NC}"; exit 0;;
esac
done
# Must be root to uninstall # Must be root to uninstall
str="Root user check"
if [[ ${EUID} -eq 0 ]]; then if [[ ${EUID} -eq 0 ]]; then
echo "::: You are root." echo -e " ${TICK} ${str}"
else else
echo "::: Sudo will be used for the uninstall." # Check if sudo is actually installed
# Check if it is actually installed # If it isn't, exit because the uninstall can not complete
# If it isn't, exit because the unnstall cannot complete
if [ -x "$(command -v sudo)" ]; then if [ -x "$(command -v sudo)" ]; then
export SUDO="sudo" export SUDO="sudo"
else else
echo "::: Please install sudo or run this as root." echo -e " ${CROSS} ${str}
Script called with non-root privileges
The Pi-hole requires elevated privleges to uninstall"
exit 1 exit 1
fi fi
fi fi
@ -54,59 +65,48 @@ elif [ -x "$(command -v apt-get)" ]; then
${SUDO} ${PKG_MANAGER} -y autoclean ${SUDO} ${PKG_MANAGER} -y autoclean
} }
else else
echo "OS distribution not supported" echo -e " ${CROSS} OS distribution not supported"
exit exit 1
fi 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"
}
removeAndPurge() { removeAndPurge() {
# Purge dependencies # Purge dependencies
echo ":::" echo ""
for i in "${PIHOLE_DEPS[@]}"; do for i in "${PIHOLE_DEPS[@]}"; do
package_check ${i} > /dev/null package_check ${i} > /dev/null
if [ $? -eq 0 ]; then if [[ "$?" -eq 0 ]]; then
while true; do while true; do
read -rp "::: Do you wish to remove ${i} from your system? [y/n]: " yn read -rp " ${QST} Do you wish to remove ${COL_WHITE}${i}${COL_NC} from your system? [Y/N] " yn
case ${yn} in case ${yn} in
[Yy]* ) printf ":::\tRemoving %s..." "${i}"; ${SUDO} ${PKG_REMOVE} "${i}" &> /dev/null & spinner $!; printf "done!\n"; break;; [Yy]* )
[Nn]* ) printf ":::\tSkipping %s\n" "${i}"; break;; echo -ne " ${INFO} Removing ${i}...";
* ) printf "::: You must answer yes or no!\n";; ${SUDO} ${PKG_REMOVE} "${i}" &> /dev/null;
echo -e "${OVER} ${INFO} Removed ${i}";
break;;
[Nn]* ) echo -e " ${INFO} Skipped ${i}"; break;;
esac esac
done done
else else
printf ":::\tPackage %s not installed... Not removing.\n" "${i}" echo -e " ${INFO} Package ${i} not installed"
fi fi
done done
# Remove dependency config files # Remove dnsmasq config files
echo "::: Removing dnsmasq config files..."
${SUDO} rm /etc/dnsmasq.conf /etc/dnsmasq.conf.orig /etc/dnsmasq.d/01-pihole.conf &> /dev/null ${SUDO} rm /etc/dnsmasq.conf /etc/dnsmasq.conf.orig /etc/dnsmasq.d/01-pihole.conf &> /dev/null
echo -e " ${TICK} Removing dnsmasq config files"
# Take care of any additional package cleaning # Take care of any additional package cleaning
printf "::: Auto removing & cleaning remaining dependencies..." echo -ne " ${INFO} Removing & cleaning remaining dependencies..."
package_cleanup &> /dev/null & spinner $!; printf "done!\n"; package_cleanup &> /dev/null
echo -e "${OVER} ${TICK} Removed & cleaned up remaining dependencies"
# Call removeNoPurge to remove PiHole specific files
# Call removeNoPurge to remove Pi-hole specific files
removeNoPurge removeNoPurge
} }
removeNoPurge() { removeNoPurge() {
echo ":::" # Only web directories/files that are created by Pi-hole should be removed
# Only web directories/files that are created by pihole should be removed. echo -ne " ${INFO} Removing Web Interface..."
echo "::: Removing the Pi-hole Web server files..."
${SUDO} rm -rf /var/www/html/admin &> /dev/null ${SUDO} rm -rf /var/www/html/admin &> /dev/null
${SUDO} rm -rf /var/www/html/pihole &> /dev/null ${SUDO} rm -rf /var/www/html/pihole &> /dev/null
${SUDO} rm /var/www/html/index.lighttpd.orig &> /dev/null ${SUDO} rm /var/www/html/index.lighttpd.orig &> /dev/null
@ -117,34 +117,35 @@ removeNoPurge() {
${SUDO} rm -rf /var/www/html &> /dev/null ${SUDO} rm -rf /var/www/html &> /dev/null
fi fi
fi fi
echo -e "${OVER} ${TICK} Removed Web Interface"
# Attempt to preserve backwards compatibility with older versions # Attempt to preserve backwards compatibility with older versions
# to guarantee no additional changes were made to /etc/crontab after # to guarantee no additional changes were made to /etc/crontab after
# the installation of pihole, /etc/crontab.pihole should be permanently # the installation of pihole, /etc/crontab.pihole should be permanently
# preserved. # preserved.
if [[ -f /etc/crontab.orig ]]; then if [[ -f /etc/crontab.orig ]]; then
echo "::: Initial Pi-hole cron detected. Restoring the default system cron..."
${SUDO} mv /etc/crontab /etc/crontab.pihole ${SUDO} mv /etc/crontab /etc/crontab.pihole
${SUDO} mv /etc/crontab.orig /etc/crontab ${SUDO} mv /etc/crontab.orig /etc/crontab
${SUDO} service cron restart ${SUDO} service cron restart
echo -e " ${TICK} Restored the default system cron"
fi fi
# Attempt to preserve backwards compatibility with older versions # Attempt to preserve backwards compatibility with older versions
if [[ -f /etc/cron.d/pihole ]];then if [[ -f /etc/cron.d/pihole ]];then
echo "::: Removing cron.d/pihole..."
${SUDO} rm /etc/cron.d/pihole &> /dev/null ${SUDO} rm /etc/cron.d/pihole &> /dev/null
echo -e " ${TICK} Removed /etc/cron.d/pihole"
fi fi
echo "::: Removing config files and scripts..."
package_check lighttpd > /dev/null package_check lighttpd > /dev/null
if [ $? -eq 1 ]; then if [[ $? -eq 1 ]]; then
${SUDO} rm -rf /etc/lighttpd/ &> /dev/null ${SUDO} rm -rf /etc/lighttpd/ &> /dev/null
echo -e " ${TICK} Removed lighttpd"
else else
if [ -f /etc/lighttpd/lighttpd.conf.orig ]; then if [ -f /etc/lighttpd/lighttpd.conf.orig ]; then
${SUDO} mv /etc/lighttpd/lighttpd.conf.orig /etc/lighttpd/lighttpd.conf ${SUDO} mv /etc/lighttpd/lighttpd.conf.orig /etc/lighttpd/lighttpd.conf
fi fi
fi fi
${SUDO} rm /etc/dnsmasq.d/adList.conf &> /dev/null ${SUDO} rm /etc/dnsmasq.d/adList.conf &> /dev/null
${SUDO} rm /etc/dnsmasq.d/01-pihole.conf &> /dev/null ${SUDO} rm /etc/dnsmasq.d/01-pihole.conf &> /dev/null
${SUDO} rm -rf /var/log/*pihole* &> /dev/null ${SUDO} rm -rf /var/log/*pihole* &> /dev/null
@ -154,28 +155,53 @@ removeNoPurge() {
${SUDO} rm /usr/local/bin/pihole &> /dev/null ${SUDO} rm /usr/local/bin/pihole &> /dev/null
${SUDO} rm /etc/bash_completion.d/pihole &> /dev/null ${SUDO} rm /etc/bash_completion.d/pihole &> /dev/null
${SUDO} rm /etc/sudoers.d/pihole &> /dev/null ${SUDO} rm /etc/sudoers.d/pihole &> /dev/null
echo -e " ${TICK} Removed config files"
# Remove FTL
if command -v pihole-FTL &> /dev/null; then
echo -ne " ${INFO} Removing pihole-FTL..."
if [[ -x "$(command -v systemctl)" ]]; then
systemctl stop pihole-FTL
else
service pihole-FTL stop
fi
${SUDO} rm /etc/init.d/pihole-FTL
${SUDO} rm /usr/bin/pihole-FTL
echo -e "${OVER} ${TICK} Removed pihole-FTL"
fi
# If the pihole user exists, then remove # If the pihole user exists, then remove
if id "pihole" >/dev/null 2>&1; then if id "pihole" &> /dev/null; then
echo "::: Removing pihole user..." ${SUDO} userdel -r pihole 2> /dev/null
${SUDO} userdel -r pihole if [[ "$?" -eq 0 ]]; then
echo -e " ${TICK} Removed 'pihole' user"
else
echo -e " ${CROSS} Unable to remove 'pihole' user"
fi
fi fi
echo ":::" echo -e "\n We're sorry to see you go, but thanks for checking out Pi-hole!
printf "::: Finished removing PiHole from your system. Sorry to see you go!\n" If you need help, reach out to us on Github, Discourse, Reddit or Twitter
printf "::: Reach out to us at https://github.com/pi-hole/pi-hole/issues if you need help\n" Reinstall at any time: ${COL_WHITE}curl -sSL https://install.pi-hole.net | bash${COL_NC}
printf "::: Reinstall by simpling running\n:::\n:::\tcurl -sSL https://install.pi-hole.net | bash\n:::\n::: at any time!\n:::\n"
printf "::: PLEASE RESET YOUR DNS ON YOUR ROUTER/CLIENTS TO RESTORE INTERNET CONNECTIVITY!\n" ${COL_LIGHT_RED}Please reset the DNS on your router/clients to restore internet connectivity
${COL_LIGHT_GREEN}Uninstallation Complete! ${COL_NC}"
} }
######### SCRIPT ########### ######### SCRIPT ###########
echo "::: Preparing to remove packages, be sure that each may be safely removed depending on your operating system." if command -v vcgencmd &> /dev/null; then
echo "::: (SAFE TO REMOVE ALL ON RASPBIAN)" echo -e " ${INFO} All dependencies are safe to remove on Raspbian"
else
echo -e " ${INFO} Be sure to confirm if any dependencies should not be removed"
fi
while true; do while true; do
read -rp "::: Do you wish to purge PiHole's dependencies from your OS? (You will be prompted for each package) [y/n]: " yn read -rp " ${QST} Do you wish to go through each dependency for removal? [Y/n] " yn
case ${yn} in case ${yn} in
[Yy]* ) removeAndPurge; break;; [Yy]* ) removeAndPurge; break;;
[Nn]* ) removeNoPurge; break;; [Nn]* ) removeNoPurge; break;;
* ) removeAndPurge; break;;
esac esac
done done

@ -8,45 +8,42 @@
# This file is copyright under the latest version of the EUPL. # This file is copyright under the latest version of the EUPL.
# Please see LICENSE file for your rights under this license. # Please see LICENSE file for your rights under this license.
# Run this script as root or under sudo # Run this script as root or under sudo
echo ":::"
coltable="/opt/pihole/COL_TABLE"
source ${coltable}
helpFunc() { helpFunc() {
cat << EOM echo "Usage: pihole -g
::: Pull in domains from adlists Update domains from blocklists specified in adlists.list
:::
::: Usage: pihole -g Options:
::: -f, --force Force the download of all specified blocklists
::: Options: -h, --help Show this help dialog"
::: -f, --force Force lists to be downloaded, even if they don't need updating. exit 0
::: -h, --help Show this help dialog
EOM
exit 0
} }
PIHOLE_COMMAND="/usr/local/bin/pihole" PIHOLE_COMMAND="/usr/local/bin/pihole"
adListFile=/etc/pihole/adlists.list adListFile=/etc/pihole/adlists.list
adListDefault=/etc/pihole/adlists.default #being deprecated adListDefault=/etc/pihole/adlists.default # Deprecated
adListRepoDefault=/etc/.pihole/adlists.default adListRepoDefault=/etc/.pihole/adlists.default
whitelistScript="${PIHOLE_COMMAND} -w" whitelistScript="${PIHOLE_COMMAND} -w"
whitelistFile=/etc/pihole/whitelist.txt whitelistFile=/etc/pihole/whitelist.txt
blacklistFile=/etc/pihole/blacklist.txt blacklistFile=/etc/pihole/blacklist.txt
readonly wildcardlist="/etc/dnsmasq.d/03-pihole-wildcard.conf" readonly wildcardlist="/etc/dnsmasq.d/03-pihole-wildcard.conf"
#Source the setupVars from install script for the IP # Source the setupVars from install script for the IP
setupVars=/etc/pihole/setupVars.conf setupVars=/etc/pihole/setupVars.conf
if [[ -f ${setupVars} ]];then if [[ -f "${setupVars}" ]];then
. /etc/pihole/setupVars.conf . /etc/pihole/setupVars.conf
else else
echo "::: WARNING: /etc/pihole/setupVars.conf missing. Possible installation failure." echo -e " ${COL_LIGHT_RED}Error: /etc/pihole/setupVars.conf missing. Possible installation failure.${COL_NC}
echo "::: Please run 'pihole -r', and choose the 'reconfigure' option to reconfigure." Please run 'pihole -r', and choose the 'reconfigure' option to reconfigure."
exit 1 exit 1
fi fi
#Remove the /* from the end of the IPv4addr. # Remove the /* from the end of the IPv4addr.
IPV4_ADDRESS=${IPV4_ADDRESS%/*} IPV4_ADDRESS=${IPV4_ADDRESS%/*}
IPV6_ADDRESS=${IPV6_ADDRESS} IPV6_ADDRESS=${IPV6_ADDRESS}
@ -65,13 +62,13 @@ accretionDisc=${basename}.3.accretionDisc.txt
skipDownload=false skipDownload=false
# Warn users still using pihole.conf that it no longer has any effect (I imagine about 2 people use it) # Warn users still using pihole.conf that it no longer has any effect
if [[ -r ${piholeDir}/pihole.conf ]]; then if [[ -r ${piholeDir}/pihole.conf ]]; then
echo "::: pihole.conf file no longer supported. Over-rides in this file are ignored." echo -e " ${COL_LIGHT_RED}pihole.conf file no longer supported. Overrides in this file are ignored.${COL_NC}"
fi fi
########################### ###########################
# collapse - begin formation of pihole # Collapse - begin formation of pihole
gravity_collapse() { gravity_collapse() {
#New Logic: #New Logic:
@ -79,266 +76,276 @@ gravity_collapse() {
# If not, cp /etc/.pihole/adlists.default /etc/pihole/adlists.list # If not, cp /etc/.pihole/adlists.default /etc/pihole/adlists.list
# Read from adlists.list # Read from adlists.list
#The following two blocks will sort out any missing adlists in the /etc/pihole directory, and remove legacy adlists.default # The following two blocks will sort out any missing adlists in the /etc/pihole directory, and remove legacy adlists.default
if [ -f ${adListDefault} ] && [ -f ${adListFile} ]; then if [[ -f "${adListDefault}" ]] && [[ -f "${adListFile}" ]]; then
rm ${adListDefault} rm "${adListDefault}"
fi fi
if [ ! -f ${adListFile} ]; then if [ ! -f "${adListFile}" ]; then
cp ${adListRepoDefault} ${adListFile} cp "${adListRepoDefault}" "${adListFile}"
fi fi
echo "::: Neutrino emissions detected..." echo -e " ${INFO} Neutrino emissions detected..."
echo ":::" echo ""
echo -n "::: Pulling source lists into range..." local str="Pulling source lists into range"
echo -ne " ${INFO} ${str}..."
sources=() sources=()
while IFS= read -r line || [[ -n "$line" ]]; do while IFS= read -r line || [[ -n "$line" ]]; do
#Do not read commented out or blank lines # Do not read commented out or blank lines
if [[ ${line} = \#* ]] || [[ ! ${line} ]]; then if [[ ${line} = \#* ]] || [[ ! ${line} ]]; then
echo "" > /dev/null echo "" > /dev/null
else else
sources+=(${line}) sources+=(${line})
fi fi
done < ${adListFile} done < ${adListFile}
echo " done!"
echo -e "${OVER} ${TICK} ${str}"
} }
# patternCheck - check to see if curl downloaded any new files. # patternCheck - check to see if curl downloaded any new files.
gravity_patternCheck() { gravity_patternCheck() {
patternBuffer=$1 patternBuffer=$1
success=$2 success=$2
error=$3 error=$3
if [ $success = true ]; then if [[ "${success}" = true ]]; then
# check if download was successful but list has not been modified # Check if download was successful but list has not been modified
if [ "${error}" == "304" ]; then if [[ "${error}" == "304" ]]; then
echo "::: No changes detected, transport skipped!" echo -e " ${TICK} No changes detected, transport skipped!"
# check if the patternbuffer is a non-zero length file # Check if the patternbuffer is a non-zero length file
elif [[ -s "${patternBuffer}" ]]; then elif [[ -s "${patternBuffer}" ]]; then
# Some of the blocklists are copyright, they need to be downloaded # Some blocklists are copyright, they need to be downloaded and stored
# and stored as is. They can be processed for content after they # as is. They can be processed for content after they have been saved.
# have been saved. mv "${patternBuffer}" "${saveLocation}"
mv "${patternBuffer}" "${saveLocation}" echo -e " ${TICK} List updated, transport successful!"
echo "::: List updated, transport successful!" else
else # Empty file -> use previously downloaded list
# Empty file -> use previously downloaded list echo -e " ${INFO} Received empty file, ${COL_LIGHT_GREEN}using cached one${COL_NC} (list not updated!)"
echo "::: Received empty file, using cached one (list not updated!)" fi
fi else
else # Check if cached list exists
# check if cached list exists if [[ -r "${saveLocation}" ]]; then
if [[ -r "${saveLocation}" ]]; then echo -e " ${CROSS} List download failed, using cached list (list not updated!)"
echo "::: List download failed, using cached list (list not updated!)" else
else echo -e " ${CROSS} Download failed and no cached list available (list will not be considered)"
echo "::: Download failed and no cached list available (list will not be considered)" fi
fi fi
fi
} }
# transport - curl the specified url with any needed command extentions # transport - curl the specified url with any needed command extentions
gravity_transport() { gravity_transport() {
url=$1 url=$1
cmd_ext=$2 cmd_ext=$2
agent=$3 agent=$3
# tmp file, so we don't have to store the (long!) lists in RAM # tmp file, so we don't have to store the (long!) lists in RAM
patternBuffer=$(mktemp) patternBuffer=$(mktemp)
heisenbergCompensator="" heisenbergCompensator=""
if [[ -r ${saveLocation} ]]; then if [[ -r ${saveLocation} ]]; then
# if domain has been saved, add file for date check to only download newer # If domain has been saved, add file for date check to only download newer
heisenbergCompensator="-z ${saveLocation}" heisenbergCompensator="-z ${saveLocation}"
fi fi
# Silently curl url # Silently curl url
err=$(curl -s -L ${cmd_ext} ${heisenbergCompensator} -w %{http_code} -A "${agent}" ${url} -o ${patternBuffer}) echo -e "${OVER} ${TICK} ${str}"
local str="Status:"
echo " done" echo -ne " ${INFO} ${str} Pending"
# Analyze http response err=$(curl -s -L ${cmd_ext} ${heisenbergCompensator} -w %{http_code} -A "${agent}" ${url} -o ${patternBuffer})
echo -n "::: Status: "
case "$err" in # Analyze http response
"200" ) echo "Success (OK)"; success=true;; case "$err" in
"304" ) echo "Not modified"; success=true;; "200" ) echo -e "${OVER} ${TICK} ${str} Success (OK)"; success=true;;
"403" ) echo "Forbidden"; success=false;; "304" ) echo -e "${OVER} ${TICK} ${str} Not modified"; success=true;;
"404" ) echo "Not found"; success=false;; "403" ) echo -e "${OVER} ${CROSS} ${str} Forbidden"; success=false;;
"408" ) echo "Time-out"; success=false;; "404" ) echo -e "${OVER} ${CROSS} ${str} Not found"; success=false;;
"451" ) echo "Unavailable For Legal Reasons"; success=false;; "408" ) echo -e "${OVER} ${CROSS} ${str} Time-out"; success=false;;
"521" ) echo "Web Server Is Down (Cloudflare)"; success=false;; "451" ) echo -e "${OVER} ${CROSS} ${str} Unavailable For Legal Reasons"; success=false;;
"522" ) echo "Connection Timed Out (Cloudflare)"; success=false;; "521" ) echo -e "${OVER} ${CROSS} ${str} Web Server Is Down (Cloudflare)"; success=false;;
"500" ) echo "Internal Server Error"; success=false;; "522" ) echo -e "${OVER} ${CROSS} ${str} Connection Timed Out (Cloudflare)"; success=false;;
* ) echo "Status $err"; success=false;; "500" ) echo -e "${OVER} ${CROSS} ${str} Internal Server Error"; success=false;;
esac * ) echo -e "${OVER} ${CROSS} ${str} Status $err"; success=false;;
esac
# Process result
gravity_patternCheck "${patternBuffer}" ${success} "${err}" # Process result
gravity_patternCheck "${patternBuffer}" "${success}" "${err}"
# Delete temp file if it hasn't been moved
if [[ -f "${patternBuffer}" ]]; then # Delete temp file if it hasn't been moved
rm "${patternBuffer}" if [[ -f "${patternBuffer}" ]]; then
fi rm "${patternBuffer}"
fi
} }
# spinup - main gravity function # spinup - main gravity function
gravity_spinup() { gravity_spinup() {
echo ":::" echo ""
# Loop through domain list. Download each one and remove commented lines (lines beginning with '# 'or '/') and # blank lines # 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 for ((i = 0; i < "${#sources[@]}"; i++)); do
url=${sources[$i]} url=${sources[$i]}
# Get just the domain from the URL # Get just the domain from the URL
domain=$(echo "${url}" | cut -d'/' -f3) domain=$(cut -d'/' -f3 <<< "${url}")
# Save the file as list.#.domain # Save the file as list.#.domain
saveLocation=${piholeDir}/list.${i}.${domain}.${justDomainsExtension} saveLocation=${piholeDir}/list.${i}.${domain}.${justDomainsExtension}
activeDomains[$i]=${saveLocation} activeDomains[$i]=${saveLocation}
agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36" agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36"
# Use a case statement to download lists that need special cURL commands # Use a case statement to download lists that need special cURL commands
# to complete properly and reset the user agent when required # to complete properly and reset the user agent when required
case "${domain}" in case "${domain}" in
"adblock.mahakala.is") "pgl.yoyo.org")
agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' cmd_ext="-d mimetype=plaintext -d hostformat=hosts"
cmd_ext="-e http://forum.xda-developers.com/" ;;
;;
# Default is a simple request
"adaway.org") *) cmd_ext=""
agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' esac
;;
if [[ "${skipDownload}" == false ]]; then
"pgl.yoyo.org") local str="Aiming tractor beam at $domain"
cmd_ext="-d mimetype=plaintext -d hostformat=hosts" echo -ne " ${INFO} ${str}..."
;;
gravity_transport "$url" "$cmd_ext" "$agent" "$str"
# Default is a simple request echo ""
*) cmd_ext="" fi
esac done
if [[ "${skipDownload}" == false ]]; then
echo -n "::: Getting $domain list..."
gravity_transport "$url" "$cmd_ext" "$agent"
fi
done
} }
# Schwarzchild - aggregate domains to one list and add blacklisted domains # Schwarzchild - aggregate domains to one list and add blacklisted domains
gravity_Schwarzchild() { gravity_Schwarzchild() {
echo "::: " echo ""
# Find all active domains and compile them into one file and remove CRs # Find all active domains and compile them into one file and remove CRs
echo -n "::: Aggregating list of domains..." local str="Aggregating list of domains"
truncate -s 0 ${piholeDir}/${matterAndLight} echo -ne " ${INFO} ${str}..."
for i in "${activeDomains[@]}"; do
# Only assimilate list if it is available (download might have faild permanently) truncate -s 0 ${piholeDir}/${matterAndLight}
if [[ -r "${i}" ]]; then for i in "${activeDomains[@]}"; do
cat "${i}" | tr -d '\r' >> ${piholeDir}/${matterAndLight} # Only assimilate list if it is available (download might have failed permanently)
fi if [[ -r "${i}" ]]; then
done cat "${i}" | tr -d '\r' >> ${piholeDir}/${matterAndLight}
echo " done!" fi
done
echo -e "${OVER} ${TICK} ${str}"
} }
gravity_Blacklist() { gravity_Blacklist() {
# Append blacklist entries to eventHorizon if they exist # Append blacklist entries to eventHorizon if they exist
if [[ -f "${blacklistFile}" ]]; then if [[ -f "${blacklistFile}" ]]; then
numBlacklisted=$(wc -l < "${blacklistFile}") numBlacklisted=$(wc -l < "${blacklistFile}")
plural=; [[ "$numBlacklisted" != "1" ]] && plural=s plural=; [[ "$numBlacklisted" != "1" ]] && plural=s
echo "::: Exact blocked domain${plural}: $numBlacklisted" local str="Exact blocked domain${plural}: $numBlacklisted"
else echo -e " ${INFO} ${str}"
echo "::: Nothing to blacklist!" else
fi echo -e " ${INFO} Nothing to blacklist!"
fi
} }
gravity_Wildcard() { gravity_Wildcard() {
# Return number of wildcards in output - don't actually handle wildcards # Return number of wildcards in output - don't actually handle wildcards
if [[ -f "${wildcardlist}" ]]; then if [[ -f "${wildcardlist}" ]]; then
numWildcards=$(grep -c ^ "${wildcardlist}") numWildcards=$(grep -c ^ "${wildcardlist}")
if [[ -n "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then if [[ -n "${IPV4_ADDRESS}" ]] && [[ -n "${IPV6_ADDRESS}" ]];then
let numWildcards/=2 let numWildcards/=2
fi fi
plural=; [[ "$numWildcards" != "1" ]] && plural=s plural=; [[ "$numWildcards" != "1" ]] && plural=s
echo "::: Wildcard blocked domain${plural}: $numWildcards" echo -e " ${INFO} Wildcard blocked domain${plural}: $numWildcards"
else else
echo "::: No wildcards used!" echo -e " ${INFO} No wildcards used!"
fi fi
} }
gravity_Whitelist() { gravity_Whitelist() {
#${piholeDir}/${eventHorizon}) echo ""
echo ":::" # Prevent our sources from being pulled into the hole
# Prevent our sources from being pulled into the hole plural=; [[ "${sources[@]}" != "1" ]] && plural=s
plural=; [[ "${sources[@]}" != "1" ]] && plural=s local str="Adding adlist source${plural} to the whitelist"
echo -n "::: Adding adlist source${plural} to the whitelist..." echo -ne " ${INFO} ${str}..."
urls=() urls=()
for url in "${sources[@]}"; do for url in "${sources[@]}"; do
tmp=$(echo "${url}" | awk -F '/' '{print $3}') tmp=$(awk -F '/' '{print $3}' <<< "${url}")
urls=("${urls[@]}" ${tmp}) urls=("${urls[@]}" ${tmp})
done done
echo " done!"
echo -e "${OVER} ${TICK} ${str}"
# Ensure adlist domains are in whitelist.txt
${whitelistScript} -nr -q "${urls[@]}" > /dev/null # Ensure adlist domains are in whitelist.txt
${whitelistScript} -nr -q "${urls[@]}" > /dev/null
# Check whitelist.txt exists.
if [[ -f "${whitelistFile}" ]]; then # Check whitelist.txt exists.
# Remove anything in whitelist.txt from the Event Horizon if [[ -f "${whitelistFile}" ]]; then
numWhitelisted=$(wc -l < "${whitelistFile}") # Remove anything in whitelist.txt from the Event Horizon
plural=; [[ "$numWhitelisted" != "1" ]] && plural=s numWhitelisted=$(wc -l < "${whitelistFile}")
echo -n "::: Whitelisting $numWhitelisted domain${plural}..." plural=; [[ "$numWhitelisted" != "1" ]] && plural=s
#print everything from preEventHorizon into eventHorizon EXCEPT domains in whitelist.txt local str="Whitelisting $numWhitelisted domain${plural}"
grep -F -x -v -f ${whitelistFile} ${piholeDir}/${preEventHorizon} > ${piholeDir}/${eventHorizon} echo -ne " ${INFO} ${str}..."
echo " done!"
else # Print everything from preEventHorizon into eventHorizon EXCEPT domains in whitelist.txt
echo "::: Nothing to whitelist!" grep -F -x -v -f ${whitelistFile} ${piholeDir}/${preEventHorizon} > ${piholeDir}/${eventHorizon}
fi
echo -e "${OVER} ${TICK} ${str}"
else
echo -e " ${INFO} Nothing to whitelist!"
fi
} }
gravity_unique() { gravity_unique() {
# Sort and remove duplicates # Sort and remove duplicates
echo -n "::: Removing duplicate domains...." local str="Removing duplicate domains"
sort -u ${piholeDir}/${supernova} > ${piholeDir}/${preEventHorizon} echo -ne " ${INFO} ${str}..."
echo " done!"
numberOf=$(wc -l < ${piholeDir}/${preEventHorizon}) sort -u ${piholeDir}/${supernova} > ${piholeDir}/${preEventHorizon}
echo "::: $numberOf unique domains trapped in the event horizon."
echo -e "${OVER} ${TICK} ${str}"
numberOf=$(wc -l < ${piholeDir}/${preEventHorizon})
echo -e " ${INFO} ${COL_LIGHT_BLUE}${numberOf}${COL_NC} unique domains trapped in the event horizon."
} }
gravity_doHostFormat() { gravity_doHostFormat() {
# Check vars from setupVars.conf to see if we're using IPv4, IPv6, Or both. # Check vars from setupVars.conf to see if we're using IPv4, IPv6, Or both.
if [[ -n "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then if [[ -n "${IPV4_ADDRESS}" ]] && [[ -n "${IPV6_ADDRESS}" ]];then
# Both IPv4 and IPv6 # Both IPv4 and IPv6
awk -v ipv4addr="$IPV4_ADDRESS" -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> "${2}" < "${1}" awk -v ipv4addr="$IPV4_ADDRESS" -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> "${2}" < "${1}"
elif [[ -n "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then elif [[ -n "${IPV4_ADDRESS}" ]] && [[ -z "${IPV6_ADDRESS}" ]];then
# Only IPv4 # Only IPv4
awk -v ipv4addr="$IPV4_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0}' >> "${2}" < "${1}" awk -v ipv4addr="$IPV4_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0}' >> "${2}" < "${1}"
elif [[ -z "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then elif [[ -z "${IPV4_ADDRESS}" ]] && [[ -n "${IPV6_ADDRESS}" ]];then
# Only IPv6 # Only IPv6
awk -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv6addr" "$0}' >> "${2}" < "${1}" awk -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv6addr" "$0}' >> "${2}" < "${1}"
elif [[ -z "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then elif [[ -z "${IPV4_ADDRESS}" ]] &&[[ -z "${IPV6_ADDRESS}" ]];then
echo "::: No IP Values found! Please run 'pihole -r' and choose reconfigure to restore values" echo -e "${OVER} ${CROSS} ${str}"
exit 1 echo -e " ${COL_LIGHT_RED}No IP Values found! Please run 'pihole -r' and choose reconfigure to restore values${COL_NC}"
exit 1
fi fi
} }
gravity_hostFormatLocal() { gravity_hostFormatLocal() {
# Format domain list as "192.168.x.x domain.com" # Format domain list as "192.168.x.x domain.com"
if [[ -f /etc/hostname ]]; then if [[ -f "/etc/hostname" ]]; then
hostname=$(</etc/hostname) hostname=$(< /etc/hostname)
elif [ -x "$(command -v hostname)" ]; then elif [ -x "$(command -v hostname)" ]; then
hostname=$(hostname -f) hostname=$(hostname -f)
else else
echo "::: Error: Unable to determine fully qualified domain name of host" echo -e " ${CROSS} Unable to determine fully qualified domain name of host"
fi fi
echo -e "${hostname}\npi.hole" > "${localList}.tmp" echo -e "${hostname}\npi.hole" > "${localList}.tmp"
# Copy the file over as /etc/pihole/local.list so dnsmasq can use it # Copy the file over as /etc/pihole/local.list so dnsmasq can use it
rm "${localList}" rm "${localList}"
gravity_doHostFormat "${localList}.tmp" "${localList}" gravity_doHostFormat "${localList}.tmp" "${localList}"
rm "${localList}.tmp" rm "${localList}.tmp"
} }
gravity_hostFormatGravity() { gravity_hostFormatGravity() {
# Format domain list as "192.168.x.x domain.com" # Format domain list as "192.168.x.x domain.com"
echo "" > "${piholeDir}/${accretionDisc}" echo "" > "${piholeDir}/${accretionDisc}"
gravity_doHostFormat "${piholeDir}/${eventHorizon}" "${piholeDir}/${accretionDisc}" gravity_doHostFormat "${piholeDir}/${eventHorizon}" "${piholeDir}/${accretionDisc}"
# Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it # Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it
mv "${piholeDir}/${accretionDisc}" "${adList}" mv "${piholeDir}/${accretionDisc}" "${adList}"
} }
gravity_hostFormatBlack() { gravity_hostFormatBlack() {
@ -349,76 +356,83 @@ gravity_hostFormatBlack() {
# Copy the file over as /etc/pihole/black.list so dnsmasq can use it # Copy the file over as /etc/pihole/black.list so dnsmasq can use it
mv "${blackList}.tmp" "${blackList}" mv "${blackList}.tmp" "${blackList}"
else else
echo "::: Nothing to blacklist!" echo -e " ${INFO} Nothing to blacklist!"
fi fi
} }
# blackbody - remove any remnant files from script processes # blackbody - remove any remnant files from script processes
gravity_blackbody() { gravity_blackbody() {
# Loop through list files # 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 list is in active array then leave it (noop) else rm the list
if [[ " ${activeDomains[@]} " =~ ${file} ]]; then if [[ " ${activeDomains[@]} " =~ ${file} ]]; then
: :
else else
rm -f "${file}" rm -f "${file}"
fi fi
done done
} }
gravity_advanced() { gravity_advanced() {
# Remove comments and print only the domain name # Remove comments and print only the domain name
# Most of the lists downloaded are already in hosts file format but the spacing/formating is not contigious # Most of the lists downloaded are already in hosts file format but the spacing/formating is not contigious
# This helps with that and makes it easier to read # This helps with that and makes it easier to read
# It also helps with debugging so each stage of the script can be researched more in depth # It also helps with debugging so each stage of the script can be researched more in depth
echo -n "::: Formatting list of domains to remove comments...." local str="Formatting list of domains to remove comments"
#awk '($1 !~ /^#/) { if (NF>1) {print $2} else {print $1}}' ${piholeDir}/${matterAndLight} | sed -nr -e 's/\.{2,}/./g' -e '/\./p' > ${piholeDir}/${supernova} echo -ne " ${INFO} ${str}..."
#Above line does not correctly grab domains where comment is on the same line (e.g 'addomain.com #comment')
#Awk -F splits on given IFS, we grab the right hand side (chops trailing #coments and /'s to grab the domain only. #awk '($1 !~ /^#/) { if (NF>1) {print $2} else {print $1}}' ${piholeDir}/${matterAndLight} | sed -nr -e 's/\.{2,}/./g' -e '/\./p' > ${piholeDir}/${supernova}
#Last awk command takes non-commented lines and if they have 2 fields, take the left field (the domain) and leave #Above line does not correctly grab domains where comment is on the same line (e.g 'addomain.com #comment')
#+ the right (IP address), otherwise grab the single field. #Awk -F splits on given IFS, we grab the right hand side (chops trailing #coments and /'s to grab the domain only.
cat ${piholeDir}/${matterAndLight} | \ #Last awk command takes non-commented lines and if they have 2 fields, take the left field (the domain) and leave
awk -F '#' '{print $1}' | \ #+ the right (IP address), otherwise grab the single field.
awk -F '/' '{print $1}' | \ cat ${piholeDir}/${matterAndLight} | \
awk '($1 !~ /^#/) { if (NF>1) {print $2} else {print $1}}' | \ awk -F '#' '{print $1}' | \
sed -nr -e 's/\.{2,}/./g' -e '/\./p' > ${piholeDir}/${supernova} awk -F '/' '{print $1}' | \
echo " done!" awk '($1 !~ /^#/) { if (NF>1) {print $2} else {print $1}}' | \
sed -nr -e 's/\.{2,}/./g' -e '/\./p' > ${piholeDir}/${supernova}
numberOf=$(wc -l < ${piholeDir}/${supernova})
echo "::: ${numberOf} domains being pulled in by gravity..." echo -e "${OVER} ${TICK} ${str}"
gravity_unique numberOf=$(wc -l < ${piholeDir}/${supernova})
echo -e " ${INFO} ${COL_LIGHT_BLUE}${numberOf}${COL_NC} domains being pulled in by gravity"
gravity_unique
} }
gravity_reload() { gravity_reload() {
# Reload hosts file
# Reload hosts file echo ""
echo ":::" local str="Refreshing lists in dnsmasq"
echo -n "::: Refresh lists in dnsmasq..." echo -e " ${INFO} ${str}..."
#ensure /etc/dnsmasq.d/01-pihole.conf is pointing at the correct list! # Ensure /etc/dnsmasq.d/01-pihole.conf is pointing at the correct list!
#First escape forward slashes in the path: # First escape forward slashes in the path:
adList=${adList//\//\\\/} adList=${adList//\//\\\/}
#Now replace the line in dnsmasq file # Now replace the line in dnsmasq file
# sed -i "s/^addn-hosts.*/addn-hosts=$adList/" /etc/dnsmasq.d/01-pihole.conf # sed -i "s/^addn-hosts.*/addn-hosts=$adList/" /etc/dnsmasq.d/01-pihole.conf
"${PIHOLE_COMMAND}" restartdns "${PIHOLE_COMMAND}" restartdns
echo " done!"
} }
for var in "$@"; do for var in "$@"; do
case "${var}" in case "${var}" in
"-f" | "--force" ) forceGrav=true;; "-f" | "--force" ) forceGrav=true;;
"-h" | "--help" ) helpFunc;; "-h" | "--help" ) helpFunc;;
"-sd" | "--skip-download" ) skipDownload=true;; "-sd" | "--skip-download" ) skipDownload=true;;
"-b" | "--blacklist-only" ) blackListOnly=true;; "-b" | "--blacklist-only" ) blackListOnly=true;;
esac esac
done done
if [[ "${forceGrav}" == true ]]; then if [[ "${forceGrav}" == true ]]; then
echo -n "::: Deleting exising list cache..." str="Deleting exising list cache"
rm /etc/pihole/list.* echo -ne "${INFO} ${str}..."
echo " done!"
if rm /etc/pihole/list.* 2> /dev/null; then
echo -e "${OVER} ${TICK} ${str}"
else
echo -e "${OVER} ${CROSS} ${str}"
fi
fi fi
if [[ ! "${blackListOnly}" == true ]]; then if [[ ! "${blackListOnly}" == true ]]; then
@ -428,31 +442,34 @@ if [[ ! "${blackListOnly}" == true ]]; then
gravity_Schwarzchild gravity_Schwarzchild
gravity_advanced gravity_advanced
else else
echo "::: Using cached Event Horizon list..." echo -e " ${INFO} Using cached Event Horizon list..."
numberOf=$(wc -l < ${piholeDir}/${preEventHorizon}) numberOf=$(wc -l < ${piholeDir}/${preEventHorizon})
echo "::: $numberOf unique domains trapped in the event horizon." echo -e " ${INFO} ${COL_LIGHT_BLUE}$numberOf${COL_NC} unique domains trapped in the event horizon."
fi fi
gravity_Whitelist gravity_Whitelist
fi fi
gravity_Blacklist gravity_Blacklist
gravity_Wildcard gravity_Wildcard
echo -n "::: Formatting domains into a HOSTS file..." str="Formatting domains into a HOSTS file"
echo -ne " ${INFO} ${str}..."
if [[ ! "${blackListOnly}" == true ]]; then if [[ ! "${blackListOnly}" == true ]]; then
gravity_hostFormatLocal gravity_hostFormatLocal
gravity_hostFormatGravity gravity_hostFormatGravity
fi fi
gravity_hostFormatBlack gravity_hostFormatBlack
echo " done!" echo -e "${OVER} ${TICK} ${str}"
gravity_blackbody gravity_blackbody
if [[ ! "${blackListOnly}" == true ]]; then if [[ ! "${blackListOnly}" == true ]]; then
#Clear no longer needed files... # Clear no longer needed files...
echo ":::" str="Cleaning up un-needed files"
echo -n "::: Cleaning up un-needed files..." echo -ne " ${INFO} ${str}..."
rm ${piholeDir}/pihole.*.txt
echo " done!" rm ${piholeDir}/pihole.*.txt 2> /dev/null
echo -e "${OVER} ${TICK} ${str}"
fi fi
gravity_reload gravity_reload

107
pihole

@ -8,6 +8,9 @@
# This file is copyright under the latest version of the EUPL. # This file is copyright under the latest version of the EUPL.
# Please see LICENSE file for your rights under this license. # Please see LICENSE file for your rights under this license.
colfile="/opt/pihole/COL_TABLE"
source ${colfile}
readonly PI_HOLE_SCRIPT_DIR="/opt/pihole" readonly PI_HOLE_SCRIPT_DIR="/opt/pihole"
readonly wildcardlist="/etc/dnsmasq.d/03-pihole-wildcard.conf" readonly wildcardlist="/etc/dnsmasq.d/03-pihole-wildcard.conf"
@ -17,7 +20,7 @@ if [[ ! $EUID -eq 0 ]];then
exec sudo bash "$0" "$@" exec sudo bash "$0" "$@"
exit $? exit $?
else else
echo "::: sudo is needed to run pihole commands. Please run this script as root or install sudo." echo -e " ${CROSS} sudo is needed to run pihole commands. Please run this script as root or install sudo."
exit 1 exit 1
fi fi
fi fi
@ -108,6 +111,13 @@ processWildcards() {
queryFunc() { queryFunc() {
domain="${2}" domain="${2}"
if [[ -z "${domain}" ]]; then
echo -e " ${COL_LIGHT_RED}Invalid option${COL_NC}
Try 'pihole query --help' for more information."
exit 1
fi
method="${3}" method="${3}"
lists=( /etc/pihole/list.* /etc/pihole/blacklist.txt) lists=( /etc/pihole/list.* /etc/pihole/blacklist.txt)
for list in ${lists[@]}; do for list in ${lists[@]}; do
@ -115,13 +125,13 @@ queryFunc() {
result=$(scanList ${domain} ${list} ${method}) result=$(scanList ${domain} ${list} ${method})
# Remove empty lines before couting number of results # Remove empty lines before couting number of results
count=$(sed '/^\s*$/d' <<< "$result" | wc -l) count=$(sed '/^\s*$/d' <<< "$result" | wc -l)
echo "::: ${list} (${count} results)" echo "${list} (${count} results)"
if [[ ${count} > 0 ]]; then if [[ ${count} > 0 ]]; then
echo "${result}" echo "${result}"
fi fi
echo "" echo ""
else else
echo "::: ${list} does not exist" echo -e " ${CROSS} List does not exist"
echo "" echo ""
fi fi
done done
@ -134,7 +144,7 @@ queryFunc() {
# Remove empty lines before couting number of results # Remove empty lines before couting number of results
count=$(sed '/^\s*$/d' <<< "$result" | wc -l) count=$(sed '/^\s*$/d' <<< "$result" | wc -l)
if [[ ${count} > 0 ]]; then if [[ ${count} > 0 ]]; then
echo "::: Wildcard blocking ${domain} (${count} results)" echo -e " ${TICK} Wildcard blocking ${domain} (${count} results)"
echo "${result}" echo "${result}"
echo "" echo ""
fi fi
@ -165,18 +175,22 @@ restartDNS() {
dnsmasqPid=$(pidof dnsmasq) dnsmasqPid=$(pidof dnsmasq)
if [[ "${dnsmasqPid}" ]]; then if [[ "${dnsmasqPid}" ]]; then
# Service already running - reload config # Service already running - reload config
echo -ne " ${INFO} Restarting dnsmasq"
if [[ -x "$(command -v systemctl)" ]]; then if [[ -x "$(command -v systemctl)" ]]; then
systemctl restart dnsmasq systemctl restart dnsmasq
else else
service dnsmasq restart service dnsmasq restart
fi fi
[[ "$?" == 0 ]] && echo -e "${OVER} ${TICK} Restarted dnsmasq" || echo -e "${OVER} ${CROSS} Failed to restart dnsmasq"
else else
# Service not running, start it up # Service not running, start it up
echo -ne " ${INFO} Starting dnsmasq"
if [[ -x "$(command -v systemctl)" ]]; then if [[ -x "$(command -v systemctl)" ]]; then
systemctl start dnsmasq systemctl start dnsmasq
else else
service dnsmasq start service dnsmasq start
fi fi
[[ "$?" == 0 ]] && echo -e "${OVER} ${TICK} Restarted dnsmasq" || echo -e "${OVER} ${CROSS} Failed to restart dnsmasq"
fi fi
} }
@ -190,6 +204,7 @@ Time:
#s Disable Pi-hole functionality for # second(s) #s Disable Pi-hole functionality for # second(s)
#m Disable Pi-hole functionality for # minute(s)" #m Disable Pi-hole functionality for # minute(s)"
exit 0 exit 0
elif [[ "${1}" == "0" ]]; then elif [[ "${1}" == "0" ]]; then
# Disable Pi-hole # Disable Pi-hole
sed -i 's/^addn-hosts=\/etc\/pihole\/gravity.list/#addn-hosts=\/etc\/pihole\/gravity.list/' /etc/dnsmasq.d/01-pihole.conf sed -i 's/^addn-hosts=\/etc\/pihole\/gravity.list/#addn-hosts=\/etc\/pihole\/gravity.list/' /etc/dnsmasq.d/01-pihole.conf
@ -197,34 +212,57 @@ Time:
if [[ -e "$wildcardlist" ]]; then if [[ -e "$wildcardlist" ]]; then
mv "$wildcardlist" "/etc/pihole/wildcard.list" mv "$wildcardlist" "/etc/pihole/wildcard.list"
fi fi
echo "::: Blocking has been disabled!"
if [[ $# > 1 ]]; then if [[ $# > 1 ]]; then
if [[ "${2}" == *"s"* ]]; then local error=false
if [[ "${2}" == *"s" ]]; then
tt=${2%"s"} tt=${2%"s"}
echo "::: Blocking will be re-enabled in ${tt} seconds" if [[ "${tt}" =~ ^-?[0-9]+$ ]];then
nohup bash -c "sleep ${tt}; pihole enable" </dev/null &>/dev/null & local str="Disabling blocking for ${tt} seconds"
elif [[ "${2}" == *"m"* ]]; then echo -e " ${INFO} ${str}..."
local str="Blocking will be re-enabled in ${tt} seconds"
nohup bash -c "sleep ${tt}; pihole enable" </dev/null &>/dev/null &
else
local error=true
fi
elif [[ "${2}" == *"m" ]]; then
tt=${2%"m"} tt=${2%"m"}
echo "::: Blocking will be re-enabled in ${tt} minutes" if [[ "${tt}" =~ ^-?[0-9]+$ ]];then
tt=$((${tt}*60)) local str="Disabling blocking for ${tt} minutes"
nohup bash -c "sleep ${tt}; pihole enable" </dev/null &>/dev/null & echo -e " ${INFO} ${str}..."
local str="Blocking will be re-enabled in ${tt} minutes"
tt=$((${tt}*60))
nohup bash -c "sleep ${tt}; pihole enable" </dev/null &>/dev/null &
else
local error=true
fi
elif [[ -n "${2}" ]]; then
local error=true
else else
echo "::: Unknown format for delayed reactivation of the blocking!" echo -e " ${INFO} Disabling blocking"
echo "::: Example:"
echo "::: pihole disable 5s - will disable blocking for 5 seconds"
echo "::: pihole disable 7m - will disable blocking for 7 minutes"
echo "::: Blocking will not automatically be re-enabled!"
fi fi
if [[ ${error} == true ]];then
echo -e " ${COL_LIGHT_RED}Unknown format for delayed reactivation of the blocking!${COL_NC}"
echo -e " Try 'pihole disable --help' for more information."
exit 1
fi
local str="Pi-hole Disabled"
fi fi
else else
# Enable Pi-hole # Enable Pi-hole
echo "::: Blocking has been enabled!" echo -e " ${INFO} Enabling blocking"
local str="Pi-hole Enabled"
sed -i 's/^#addn-hosts/addn-hosts/' /etc/dnsmasq.d/01-pihole.conf sed -i 's/^#addn-hosts/addn-hosts/' /etc/dnsmasq.d/01-pihole.conf
if [[ -e "/etc/pihole/wildcard.list" ]]; then if [[ -e "/etc/pihole/wildcard.list" ]]; then
mv "/etc/pihole/wildcard.list" "$wildcardlist" mv "/etc/pihole/wildcard.list" "$wildcardlist"
fi fi
fi fi
restartDNS restartDNS
echo -e "${OVER} ${TICK} ${str}"
} }
piholeLogging() { piholeLogging() {
@ -243,29 +281,33 @@ Options:
sed -i 's/^log-queries/#log-queries/' /etc/dnsmasq.d/01-pihole.conf sed -i 's/^log-queries/#log-queries/' /etc/dnsmasq.d/01-pihole.conf
sed -i 's/^QUERY_LOGGING=true/QUERY_LOGGING=false/' /etc/pihole/setupVars.conf sed -i 's/^QUERY_LOGGING=true/QUERY_LOGGING=false/' /etc/pihole/setupVars.conf
pihole -f pihole -f
echo "::: Logging has been disabled!" echo -e " ${INFO} Disabling logging..."
local str="Logging has been disabled!"
elif [[ "${1}" == "on" ]]; then elif [[ "${1}" == "on" ]]; then
# Enable logging # Enable logging
sed -i 's/^#log-queries/log-queries/' /etc/dnsmasq.d/01-pihole.conf sed -i 's/^#log-queries/log-queries/' /etc/dnsmasq.d/01-pihole.conf
sed -i 's/^QUERY_LOGGING=false/QUERY_LOGGING=true/' /etc/pihole/setupVars.conf sed -i 's/^QUERY_LOGGING=false/QUERY_LOGGING=true/' /etc/pihole/setupVars.conf
echo "::: Logging has been enabled!" echo -e " ${INFO} Enabling logging..."
local str="Logging has been enabled!"
else else
echo "::: Invalid option passed, please pass 'on' or 'off'" echo -e " ${COL_LIGHT_RED}Invalid option${COL_NC}
Try 'pihole logging --help' for more information."
exit 1 exit 1
fi fi
restartDNS restartDNS
echo -e "${OVER} ${TICK} ${str}"
} }
piholeStatus() { piholeStatus() {
if [[ "$(netstat -plnt | grep -c ':53 ')" -gt "0" ]]; then if [[ "$(netstat -plnt | grep -c ':53 ')" -gt "0" ]]; then
if [[ "${1}" != "web" ]]; then if [[ "${1}" != "web" ]]; then
echo "::: DNS service is running" echo -e " ${TICK} DNS service is running"
fi fi
else else
if [[ "${1}" == "web" ]]; then if [[ "${1}" == "web" ]]; then
echo "-1"; echo "-1";
else else
echo "::: DNS service is NOT running" echo -e " ${CROSS} DNS service is NOT running"
fi fi
return return
fi fi
@ -275,21 +317,21 @@ piholeStatus() {
if [[ "${1}" == "web" ]]; then if [[ "${1}" == "web" ]]; then
echo 0; echo 0;
else else
echo "::: Pi-hole blocking is Disabled"; echo -e " ${CROSS} Pi-hole blocking is Disabled";
fi fi
elif [[ "$(grep -i "^addn-hosts=/" /etc/dnsmasq.d/01-pihole.conf)" ]]; then elif [[ "$(grep -i "^addn-hosts=/" /etc/dnsmasq.d/01-pihole.conf)" ]]; then
# List set # List set
if [[ "${1}" == "web" ]]; then if [[ "${1}" == "web" ]]; then
echo 1; echo 1;
else else
echo "::: Pi-hole blocking is Enabled"; echo -e " ${TICK} Pi-hole blocking is Enabled";
fi fi
else else
# Addn-host not found # Addn-host not found
if [[ "${1}" == "web" ]]; then if [[ "${1}" == "web" ]]; then
echo 99 echo 99
else else
echo "::: No hosts file linked to dnsmasq, adding it in enabled state" echo -e " ${INFO} No hosts file linked to dnsmasq, adding it in enabled state"
fi fi
# Add addn-host= to dnsmasq # Add addn-host= to dnsmasq
echo "addn-hosts=/etc/pihole/gravity.list" >> /etc/dnsmasq.d/01-pihole.conf echo "addn-hosts=/etc/pihole/gravity.list" >> /etc/dnsmasq.d/01-pihole.conf
@ -298,7 +340,7 @@ piholeStatus() {
} }
tailFunc() { tailFunc() {
echo "Press Ctrl-C to exit" echo -e " ${INFO} Press Ctrl-C to exit"
tail -F /var/log/pihole.log tail -F /var/log/pihole.log
exit 0 exit 0
} }
@ -326,12 +368,12 @@ Branches:
tricorderFunc() { tricorderFunc() {
if [[ ! -p "/dev/stdin" ]]; then if [[ ! -p "/dev/stdin" ]]; then
echo "Please do not call Tricorder directly." echo -e " ${INFO} Please do not call Tricorder directly"
exit 1 exit 1
fi fi
if ! timeout 2 nc -z tricorder.pi-hole.net 9998 &> /dev/null; then if ! timeout 2 nc -z tricorder.pi-hole.net 9998 &> /dev/null; then
echo "Unable to connect to Pi-hole's Tricorder server." echo -e " ${CROSS} Unable to connect to Pi-hole's Tricorder server"
exit 1 exit 1
fi fi
@ -339,9 +381,10 @@ tricorderFunc() {
openssl s_client -quiet -connect tricorder.pi-hole.net:9998 2> /dev/null < /dev/stdin openssl s_client -quiet -connect tricorder.pi-hole.net:9998 2> /dev/null < /dev/stdin
exit "$?" exit "$?"
else else
echo "Your debug log will be transmitted unencrypted via plain-text" echo -e " ${INFO} ${COL_YELLOW}Security Notice${COL_NC}: ${COL_WHITE}openssl${COL_NC} is not installed
echo "There is a possibility that this could be intercepted by a third party" Your debug log will be transmitted unencrypted via plain-text
echo "If you wish to cancel, press Ctrl-C to exit within 10 seconds" There is a possibility that this could be intercepted by a third party
If you wish to cancel, press Ctrl-C to exit within 10 seconds"
secs="10" secs="10"
while [[ "$secs" -gt "0" ]]; do while [[ "$secs" -gt "0" ]]; do
echo -ne "." echo -ne "."

@ -9,6 +9,10 @@ SETUPVARS = {
'PIHOLE_DNS_2' : '4.2.2.2' 'PIHOLE_DNS_2' : '4.2.2.2'
} }
tick_box="[\x1b[1;32m\xe2\x9c\x93\x1b[0m]".decode("utf-8")
cross_box="[\x1b[1;31m\xe2\x9c\x97\x1b[0m]".decode("utf-8")
info_box="[i]".decode("utf-8")
def test_setupVars_are_sourced_to_global_scope(Pihole): def test_setupVars_are_sourced_to_global_scope(Pihole):
''' currently update_dialogs sources setupVars with a dot, ''' currently update_dialogs sources setupVars with a dot,
then various other functions use the variables. then various other functions use the variables.
@ -173,8 +177,11 @@ def test_installPiholeWeb_fresh_install_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
installPiholeWeb installPiholeWeb
''') ''')
assert 'Installing pihole custom index page...' in installWeb.stdout assert info_box + ' Installing blocking page...' in installWeb.stdout
assert tick_box + ' Creating directory for blocking page, and copying files' in installWeb.stdout
assert cross_box + ' Backing up index.lighttpd.html' in installWeb.stdout
assert 'No default index.lighttpd.html file found... not backing up' in installWeb.stdout assert 'No default index.lighttpd.html file found... not backing up' in installWeb.stdout
assert tick_box + ' Installing sudoer file' in installWeb.stdout
web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout
assert 'index.php' in web_directory assert 'index.php' in web_directory
assert 'index.js' in web_directory assert 'index.js' in web_directory
@ -187,11 +194,12 @@ def test_installPiholeWeb_empty_directory_no_errors(Pihole):
mkdir -p /var/www/html/pihole mkdir -p /var/www/html/pihole
installPiholeWeb installPiholeWeb
''') ''')
assert 'Installing pihole custom index page...' in installWeb.stdout assert info_box + ' Installing blocking page...' in installWeb.stdout
assert info_box + ' Installing index.php' in installWeb.stdout
assert info_box + ' Installing index.js' in installWeb.stdout
assert info_box + ' Installing blockingpage.css' in installWeb.stdout
assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout
assert 'index.php missing, replacing...' in installWeb.stdout assert tick_box + ' Installing sudoer file' in installWeb.stdout
assert 'index.js missing, replacing...' in installWeb.stdout
assert 'blockingpage.css missing, replacing...' in installWeb.stdout
web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout
assert 'index.php' in web_directory assert 'index.php' in web_directory
assert 'index.js' in web_directory assert 'index.js' in web_directory
@ -205,11 +213,13 @@ def test_installPiholeWeb_index_php_no_errors(Pihole):
touch /var/www/html/pihole/index.php touch /var/www/html/pihole/index.php
installPiholeWeb installPiholeWeb
''') ''')
assert 'Installing pihole custom index page...' in installWeb.stdout assert info_box + ' Installing blocking page...' in installWeb.stdout
assert info_box + ' Installing index.php' in installWeb.stdout
assert 'detected index.php, not overwriting' in installWeb.stdout
assert info_box + ' Installing index.js' in installWeb.stdout
assert info_box + ' Installing blockingpage.css' in installWeb.stdout
assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout
assert 'Existing index.php detected, not overwriting' in installWeb.stdout assert tick_box + ' Installing sudoer file' in installWeb.stdout
assert 'index.js missing, replacing...' in installWeb.stdout
assert 'blockingpage.css missing, replacing...' in installWeb.stdout
web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout
assert 'index.php' in web_directory assert 'index.php' in web_directory
assert 'index.js' in web_directory assert 'index.js' in web_directory
@ -223,11 +233,13 @@ def test_installPiholeWeb_index_js_no_errors(Pihole):
touch /var/www/html/pihole/index.js touch /var/www/html/pihole/index.js
installPiholeWeb installPiholeWeb
''') ''')
assert 'Installing pihole custom index page...' in installWeb.stdout assert info_box + ' Installing blocking page...' in installWeb.stdout
assert info_box + ' Installing index.php' in installWeb.stdout
assert info_box + ' Installing index.js' in installWeb.stdout
assert 'detected index.js, not overwriting' in installWeb.stdout
assert info_box + ' Installing blockingpage.css' in installWeb.stdout
assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout
assert 'index.php missing, replacing...' in installWeb.stdout assert tick_box + ' Installing sudoer file' in installWeb.stdout
assert 'Existing index.js detected, not overwriting' in installWeb.stdout
assert 'blockingpage.css missing, replacing...' in installWeb.stdout
web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout
assert 'index.php' in web_directory assert 'index.php' in web_directory
assert 'index.js' in web_directory assert 'index.js' in web_directory
@ -241,11 +253,13 @@ def test_installPiholeWeb_blockingpage_css_no_errors(Pihole):
touch /var/www/html/pihole/blockingpage.css touch /var/www/html/pihole/blockingpage.css
installPiholeWeb installPiholeWeb
''') ''')
assert 'Installing pihole custom index page...' in installWeb.stdout assert info_box + ' Installing blocking page...' in installWeb.stdout
assert info_box + ' Installing index.php' in installWeb.stdout
assert info_box + ' Installing index.js' in installWeb.stdout
assert info_box + ' Installing blockingpage.css' in installWeb.stdout
assert 'detected blockingpage.css, not overwriting' in installWeb.stdout
assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout
assert 'index.php missing, replacing...' in installWeb.stdout assert tick_box + ' Installing sudoer file' in installWeb.stdout
assert 'index.js missing, replacing...' in installWeb.stdout
assert 'Existing blockingpage.css detected, not overwriting' in installWeb.stdout
web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout
assert 'index.php' in web_directory assert 'index.php' in web_directory
assert 'index.js' in web_directory assert 'index.js' in web_directory
@ -261,14 +275,14 @@ def test_installPiholeWeb_already_populated_no_errors(Pihole):
touch /var/www/html/pihole/blockingpage.css touch /var/www/html/pihole/blockingpage.css
installPiholeWeb installPiholeWeb
''') ''')
assert 'Installing pihole custom index page...' in installWeb.stdout assert info_box + ' Installing blocking page...' in installWeb.stdout
assert 'No default index.lighttpd.html file found... not backing up' not in installWeb.stdout assert info_box + ' Installing index.php' in installWeb.stdout
assert 'Existing index.php detected, not overwriting' in installWeb.stdout assert 'detected index.php, not overwriting' in installWeb.stdout
assert 'index.php missing, replacing...' not in installWeb.stdout assert info_box + ' Installing index.js' in installWeb.stdout
assert 'Existing index.js detected, not overwriting' in installWeb.stdout assert 'detected index.js, not overwriting' in installWeb.stdout
assert 'index.js missing, replacing...' not in installWeb.stdout assert info_box + ' Installing blockingpage.css' in installWeb.stdout
assert 'Existing blockingpage.css detected, not overwriting' in installWeb.stdout assert 'detected blockingpage.css, not overwriting' in installWeb.stdout
assert 'blockingpage.css missing, replacing... ' not in installWeb.stdout assert tick_box + ' Installing sudoer file' in installWeb.stdout
web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout web_directory = Pihole.run('ls -r /var/www/html/pihole').stdout
assert 'index.php' in web_directory assert 'index.php' in web_directory
assert 'index.js' in web_directory assert 'index.js' in web_directory
@ -281,9 +295,8 @@ def test_update_package_cache_success_no_errors(Pihole):
distro_check distro_check
update_package_cache update_package_cache
''') ''')
assert 'Updating local cache of available packages...' in updateCache.stdout assert tick_box + ' Update local cache of available packages' in updateCache.stdout
assert 'ERROR' not in updateCache.stdout assert 'Error: Unable to update package cache.' not in updateCache.stdout
assert 'done!' in updateCache.stdout
def test_update_package_cache_failure_no_errors(Pihole): def test_update_package_cache_failure_no_errors(Pihole):
''' confirms package cache was not updated''' ''' confirms package cache was not updated'''
@ -293,9 +306,8 @@ def test_update_package_cache_failure_no_errors(Pihole):
distro_check distro_check
update_package_cache update_package_cache
''') ''')
assert 'Updating local cache of available packages...' in updateCache.stdout assert cross_box + ' Update local cache of available packages' in updateCache.stdout
assert 'ERROR' in updateCache.stdout assert 'Error: Unable to update package cache.' in updateCache.stdout
assert 'done!' not in updateCache.stdout
def test_FTL_detect_aarch64_no_errors(Pihole): def test_FTL_detect_aarch64_no_errors(Pihole):
''' confirms only aarch64 package is downloaded for FTL engine ''' ''' confirms only aarch64 package is downloaded for FTL engine '''
@ -307,7 +319,11 @@ def test_FTL_detect_aarch64_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
FTLdetect FTLdetect
''') ''')
expected_stdout = 'Detected ARM-aarch64 architecture' expected_stdout = info_box + ' Downloading latest version of FTL...'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Detected ARM-aarch64 architecture'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Installing FTL'
assert expected_stdout in detectPlatform.stdout assert expected_stdout in detectPlatform.stdout
def test_FTL_detect_armv6l_no_errors(Pihole): def test_FTL_detect_armv6l_no_errors(Pihole):
@ -320,7 +336,11 @@ def test_FTL_detect_armv6l_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
FTLdetect FTLdetect
''') ''')
expected_stdout = 'Detected ARM-hf architecture (armv6 or lower)' expected_stdout = info_box + ' Downloading latest version of FTL...'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Detected ARM-hf architecture (armv6 or lower)'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Installing FTL'
assert expected_stdout in detectPlatform.stdout assert expected_stdout in detectPlatform.stdout
def test_FTL_detect_armv7l_no_errors(Pihole): def test_FTL_detect_armv7l_no_errors(Pihole):
@ -333,7 +353,11 @@ def test_FTL_detect_armv7l_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
FTLdetect FTLdetect
''') ''')
expected_stdout = 'Detected ARM-hf architecture (armv7+)' expected_stdout = info_box + ' Downloading latest version of FTL...'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Detected ARM-hf architecture (armv7+)'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Installing FTL'
assert expected_stdout in detectPlatform.stdout assert expected_stdout in detectPlatform.stdout
def test_FTL_detect_x86_64_no_errors(Pihole): def test_FTL_detect_x86_64_no_errors(Pihole):
@ -342,7 +366,11 @@ def test_FTL_detect_x86_64_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
FTLdetect FTLdetect
''') ''')
expected_stdout = 'Detected x86_64 architecture' expected_stdout = info_box + ' Downloading latest version of FTL...'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Detected x86_64 architecture'
assert expected_stdout in detectPlatform.stdout
expected_stdout = tick_box + ' Installing FTL'
assert expected_stdout in detectPlatform.stdout assert expected_stdout in detectPlatform.stdout
def test_FTL_detect_unknown_no_errors(Pihole): def test_FTL_detect_unknown_no_errors(Pihole):
@ -363,9 +391,12 @@ def test_FTL_download_aarch64_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
FTLinstall pihole-FTL-aarch64-linux-gnu FTLinstall pihole-FTL-aarch64-linux-gnu
''') ''')
expected_stdout = 'done' expected_stdout = tick_box + ' Installing FTL'
assert expected_stdout in download_binary.stdout assert expected_stdout in download_binary.stdout
assert 'failed' not in download_binary.stdout error = 'Error: Download of binary from Github failed'
assert error not in download_binary.stdout
error = 'Error: URL not found'
assert error not in download_binary.stdout
def test_FTL_download_unknown_fails_no_errors(Pihole): def test_FTL_download_unknown_fails_no_errors(Pihole):
''' confirms unknown binary is not downloaded for FTL engine ''' ''' confirms unknown binary is not downloaded for FTL engine '''
@ -374,9 +405,10 @@ def test_FTL_download_unknown_fails_no_errors(Pihole):
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
FTLinstall pihole-FTL-mips FTLinstall pihole-FTL-mips
''') ''')
expected_stdout = 'failed' expected_stdout = cross_box + ' Installing FTL'
assert expected_stdout in download_binary.stdout assert expected_stdout in download_binary.stdout
assert 'done' not in download_binary.stdout error = 'Error: URL not found'
assert error in download_binary.stdout
def test_FTL_binary_installed_and_responsive_no_errors(Pihole): def test_FTL_binary_installed_and_responsive_no_errors(Pihole):
''' confirms FTL binary is copied and functional in installed location ''' ''' confirms FTL binary is copied and functional in installed location '''

Loading…
Cancel
Save