From ae30c285a23240211c4641832cec42905e5be328 Mon Sep 17 00:00:00 2001 From: Markus Napp Date: Sun, 12 Mar 2017 15:45:11 +0100 Subject: [PATCH 01/85] Fix handling of wildcard help text --- advanced/Scripts/list.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index 2ac1e805..a094becb 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -31,13 +31,16 @@ helpFunc() { if [[ ${listMain} == ${whitelist} ]]; then letter="w" word="white" + elif [[ ${listMain} == ${wildcardlist} ]]; then + letter="wild" + word="wildcard" else letter="b" word="black" fi cat << EOM -::: Immediately ${word}lists one or more domains in the hosts file +::: Immediately add one or more domains to the ${word}list ::: ::: Usage: pihole -${letter} domain1 [domain2 ...] ::: @@ -48,7 +51,7 @@ helpFunc() { ::: -h, --help Show this help dialog ::: -l, --list Display your ${word}listed domains EOM -if [[ "${letter}" == "b" ]]; then +if [[ "${letter}" == "-wild" ]]; then echo "::: -wild, --wildcard Add wildcard entry (only blacklist)" fi exit 0 From 9a475cc0107c263e814a17acd676a3f8f7ef68e1 Mon Sep 17 00:00:00 2001 From: Markus Napp Date: Sun, 12 Mar 2017 15:50:48 +0100 Subject: [PATCH 02/85] Rewrite help text for better handling of params --- advanced/Scripts/list.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index a094becb..a4611a4a 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -49,9 +49,9 @@ helpFunc() { ::: -nr, --noreload Update ${word}list without refreshing dnsmasq ::: -q, --quiet Output is less verbose ::: -h, --help Show this help dialog -::: -l, --list Display your ${word}listed domains +::: -l, --list Display domains on the ${word}list EOM -if [[ "${letter}" == "-wild" ]]; then +if [[ "${letter}" == "wild" ]]; then echo "::: -wild, --wildcard Add wildcard entry (only blacklist)" fi exit 0 From bb7a7d94efe54b27e9e58af6c42314b6c45e4723 Mon Sep 17 00:00:00 2001 From: Markus Napp Date: Sun, 12 Mar 2017 16:16:45 +0100 Subject: [PATCH 03/85] Replace misleading letter variable --- advanced/Scripts/list.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index a4611a4a..8eb0543d 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -29,20 +29,20 @@ listAlt="" helpFunc() { if [[ ${listMain} == ${whitelist} ]]; then - letter="w" + param="w" word="white" elif [[ ${listMain} == ${wildcardlist} ]]; then - letter="wild" + param="wild" word="wildcard" else - letter="b" + param="b" word="black" fi cat << EOM ::: Immediately add one or more domains to the ${word}list ::: -::: Usage: pihole -${letter} domain1 [domain2 ...] +::: Usage: pihole -${param} domain1 [domain2 ...] ::: ::: Options: ::: -d, --delmode Remove domains from the ${word}list @@ -51,7 +51,7 @@ helpFunc() { ::: -h, --help Show this help dialog ::: -l, --list Display domains on the ${word}list EOM -if [[ "${letter}" == "wild" ]]; then +if [[ "${param}" == "wild" ]]; then echo "::: -wild, --wildcard Add wildcard entry (only blacklist)" fi exit 0 From 2e398c5da472a7049f33b8e57efdb59c301e0385 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 14 Apr 2017 17:20:13 +0100 Subject: [PATCH 04/85] stash changes on branch switch, else it fails if any changes have been made. --- advanced/Scripts/piholeCheckout.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/advanced/Scripts/piholeCheckout.sh b/advanced/Scripts/piholeCheckout.sh index 09f20d6b..66e435c7 100644 --- a/advanced/Scripts/piholeCheckout.sh +++ b/advanced/Scripts/piholeCheckout.sh @@ -54,6 +54,8 @@ fetch_checkout_pull_branch() { # Set the reference for the requested branch, fetch, check it put and pull it cd "${directory}" git remote set-branches origin "${branch}" || return 1 + git stash --all --quiet &> /dev/null || return 1 + git clean --force -d || return 1 git fetch --quiet || return 1 checkout_pull_branch "${directory}" "${branch}" || return 1 } From db1e5f10ea1850f0e29a50d6f1beccbf20616e56 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Fri, 21 Apr 2017 17:08:15 +0200 Subject: [PATCH 05/85] Make changes according to comment in #1384 --- advanced/Scripts/piholeCheckout.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/advanced/Scripts/piholeCheckout.sh b/advanced/Scripts/piholeCheckout.sh index 66e435c7..c5b77368 100644 --- a/advanced/Scripts/piholeCheckout.sh +++ b/advanced/Scripts/piholeCheckout.sh @@ -54,8 +54,8 @@ fetch_checkout_pull_branch() { # Set the reference for the requested branch, fetch, check it put and pull it cd "${directory}" git remote set-branches origin "${branch}" || return 1 - git stash --all --quiet &> /dev/null || return 1 - git clean --force -d || return 1 + git stash --all --quiet &> /dev/null || true + git clean --force -d || true git fetch --quiet || return 1 checkout_pull_branch "${directory}" "${branch}" || return 1 } From a0603ad3b701abde6e392a72a407260c012a9a9c Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Tue, 2 May 2017 17:13:55 +1000 Subject: [PATCH 06/85] Update queryFunc() * Allow scanList() to search files using a wildcard by removing quotes wrapped around `${list}` * scanList() will not provide a domain ouput on each string if exact is specified (`grep -l`) * Remove unused processWildcards() function * Return a message if no domain is specified * IDN domains are converted to punycode when running a `pihole -q` search if the `python` package is available, otherwise will revert to current behaviour * Scan Blacklist & Wildcards first, exiting from search if a match is found (Fixes #1330) * Use one `grep` subshell to search for all "*.domains" lists at once (opposed to looping to get every matching file name, and then spawning a `grep` instance for every matching file) * queryFunc() will not return "(0 results)" output from files where no match is found * Sort results based off list number * Return a message if no results are found --- pihole | 83 +++++++++++++++++++++++----------------------------------- 1 file changed, 33 insertions(+), 50 deletions(-) diff --git a/pihole b/pihole index 83e13000..eaf4e955 100755 --- a/pihole +++ b/pihole @@ -84,62 +84,45 @@ scanList(){ domain="${1}" list="${2}" method="${3}" - if [[ ${method} == "-exact" ]] ; then - grep -i -E "(^|\s)${domain}($|\s)" "${list}" - else - grep -i "${domain}" "${list}" - fi -} -processWildcards() { - IFS="." read -r -a array <<< "${1}" - for (( i=${#array[@]}-1; i>=0; i-- )); do - ar="" - for (( j=${#array[@]}-1; j>${#array[@]}-i-2; j-- )); do - if [[ $j == $((${#array[@]}-1)) ]]; then - ar="${array[$j]}" - else - ar="${array[$j]}.${ar}" - fi - done - echo "${ar}" - done + if [[ ${method} == "-exact" ]]; then + grep -i -E -l "(^|\/)${domain}($|\/)" ${list} + else + grep -i "${domain}" ${list} + fi } queryFunc() { - domain="${2}" method="${3}" - lists=( /etc/pihole/list.* /etc/pihole/blacklist.txt) - for list in ${lists[@]}; do - if [ -e "${list}" ]; then - result=$(scanList ${domain} ${list} ${method}) - # Remove empty lines before couting number of results - count=$(sed '/^\s*$/d' <<< "$result" | wc -l) - echo "::: ${list} (${count} results)" - if [[ ${count} > 0 ]]; then - echo "${result}" - fi - echo "" - else - echo "::: ${list} does not exist" - echo "" - fi - done - - # Scan for possible wildcard matches - if [ -e "${wildcardlist}" ]; then - local wildcards=($(processWildcards "${domain}")) - for domain in ${wildcards[@]}; do - result=$(scanList "\/${domain}\/" ${wildcardlist}) - # Remove empty lines before couting number of results - count=$(sed '/^\s*$/d' <<< "$result" | wc -l) - if [[ ${count} > 0 ]]; then - echo "::: Wildcard blocking ${domain} (${count} results)" - echo "${result}" - echo "" - fi - done + + # If domain contains non ASCII characters, convert domain to punycode if python exists + # Cr: https://serverfault.com/a/335079 + if [ -z "${2}" ]; then + echo "::: No domain specified" + exit 1 + elif [[ ${2} = *[![:ascii:]]* ]]; then + [ `which python` ] && domain=$(python -c 'import sys;print sys.argv[1].decode("utf-8").encode("idna")' "${2}") + else + domain="${2}" fi + + # Scan Blacklist and Wildcards + lists="/etc/pihole/blacklist.txt $wildcardlist" + result=$(scanList ${domain} "${lists}" ${method}) + if [ -n "$result" ]; then + echo "$result" + exit 0 + fi + + # Scan Domains lists + result=$(scanList ${domain} "/etc/pihole/*.domains" ${method}) + if [ -n "$result" ]; then + sort -t . -k 2 -g <<< "$result" + else + [ -n "$method" ] && exact="exact " + echo "::: No ${exact}results found for ${domain}" + fi + exit 0 } From 99b23627d0d8cb6036cf69e46de042a80b570ac0 Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Fri, 5 May 2017 12:03:51 -0700 Subject: [PATCH 07/85] Update basic-install.sh --- automated install/basic-install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index c65ef49f..3ca90db6 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -408,7 +408,7 @@ setDHCPCD() { echo "interface ${PIHOLE_INTERFACE} static ip_address=${IPV4_ADDRESS} static routers=${IPv4gw} - static domain_name_servers=${IPv4gw}" | tee -a /etc/dhcpcd.conf >/dev/null + static domain_name_servers=127.0.0.1" | tee -a /etc/dhcpcd.conf >/dev/null } setStaticIPv4() { From f270f7430c655249d9274553697c558c3b9b04e9 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:10:24 +0100 Subject: [PATCH 08/85] Update block page. Allow for setupVars setting of CUSTOMBLOCKPAGE (bool) to prevent it being overwritten --- automated install/basic-install.sh | 34 +++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index c65ef49f..ca45a256 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -35,7 +35,7 @@ IPV4_ADDRESS="" IPV6_ADDRESS="" QUERY_LOGGING=true INSTALL_WEB=true - +CUSTOMBLOCKPAGE=false # Find the rows and columns will default to 80x24 is it can not be detected screen_size=$(stty size 2>/dev/null || echo 24 80) @@ -866,30 +866,48 @@ CreateLogFile() { } installPiholeWeb() { + + if [ -f ${setupVars} ]; then + . ${setupVars} + fi # Install the web interface echo ":::" - echo "::: Installing pihole custom index page..." + echo -n "::: Installing index.php..." if [ -d "/var/www/html/pihole" ]; then if [ -f "/var/www/html/pihole/index.php" ]; then - echo "::: Existing index.php detected, not overwriting" + if [[ ${CUSTOMBLOCKPAGE} == true ]]; then + echo " Existing index.php detected, not overwriting" + else + cp ${PI_HOLE_LOCAL_REPO}/advanced/index.php /var/www/html/pihole/ + echo " done!" + fi else - echo -n "::: index.php missing, replacing... " cp ${PI_HOLE_LOCAL_REPO}/advanced/index.php /var/www/html/pihole/ echo " done!" fi + echo -n "::: Installing index.js..." if [ -f "/var/www/html/pihole/index.js" ]; then - echo "::: Existing index.js detected, not overwriting" + if [[ ${CUSTOMBLOCKPAGE} == true ]]; then + echo " Existing index.js detected, not overwriting" + else + cp ${PI_HOLE_LOCAL_REPO}/advanced/index.js /var/www/html/pihole/ + echo " done!" + fi else - echo -n "::: index.js missing, replacing... " cp ${PI_HOLE_LOCAL_REPO}/advanced/index.js /var/www/html/pihole/ echo " done!" fi + echo -n "::: Installing blockingpage.css..." if [ -f "/var/www/html/pihole/blockingpage.css" ]; then - echo "::: Existing blockingpage.css detected, not overwriting" + if [[ ${CUSTOMBLOCKPAGE} == true ]]; then + echo " Existing blockingpage.css detected, not overwriting" + else + cp ${PI_HOLE_LOCAL_REPO}/advanced/blockingpage.css /var/www/html/pihole + echo " done!" + fi else - echo -n "::: blockingpage.css missing, replacing... " cp ${PI_HOLE_LOCAL_REPO}/advanced/blockingpage.css /var/www/html/pihole echo " done!" fi From 5cd2c77d9897ae84d6494a4397fbbd22013289d2 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:24:40 +0100 Subject: [PATCH 09/85] simplify --- automated install/basic-install.sh | 35 +----------------------------- 1 file changed, 1 insertion(+), 34 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index ca45a256..eaa3413d 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -874,44 +874,11 @@ installPiholeWeb() { echo ":::" echo -n "::: Installing index.php..." if [ -d "/var/www/html/pihole" ]; then - if [ -f "/var/www/html/pihole/index.php" ]; then - if [[ ${CUSTOMBLOCKPAGE} == true ]]; then - echo " Existing index.php detected, not overwriting" - else + if [[ ${CUSTOMBLOCKPAGE} == false ]]; then cp ${PI_HOLE_LOCAL_REPO}/advanced/index.php /var/www/html/pihole/ - echo " done!" - fi - else - cp ${PI_HOLE_LOCAL_REPO}/advanced/index.php /var/www/html/pihole/ - echo " done!" - fi - - echo -n "::: Installing index.js..." - if [ -f "/var/www/html/pihole/index.js" ]; then - if [[ ${CUSTOMBLOCKPAGE} == true ]]; then - echo " Existing index.js detected, not overwriting" - else cp ${PI_HOLE_LOCAL_REPO}/advanced/index.js /var/www/html/pihole/ - echo " done!" - fi - else - cp ${PI_HOLE_LOCAL_REPO}/advanced/index.js /var/www/html/pihole/ - echo " done!" - fi - - echo -n "::: Installing blockingpage.css..." - if [ -f "/var/www/html/pihole/blockingpage.css" ]; then - if [[ ${CUSTOMBLOCKPAGE} == true ]]; then - echo " Existing blockingpage.css detected, not overwriting" - else cp ${PI_HOLE_LOCAL_REPO}/advanced/blockingpage.css /var/www/html/pihole - echo " done!" fi - else - cp ${PI_HOLE_LOCAL_REPO}/advanced/blockingpage.css /var/www/html/pihole - echo " done!" - fi - else echo "::: Creating directory for blocking page" install -d /var/www/html/pihole From 41dd163453cc37a2962a6d5cbf4851f53c74c49b Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:27:33 +0100 Subject: [PATCH 10/85] further simplify --- automated install/basic-install.sh | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index eaa3413d..d603585f 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -872,15 +872,14 @@ installPiholeWeb() { fi # Install the web interface echo ":::" - echo -n "::: Installing index.php..." if [ -d "/var/www/html/pihole" ]; then if [[ ${CUSTOMBLOCKPAGE} == false ]]; then - cp ${PI_HOLE_LOCAL_REPO}/advanced/index.php /var/www/html/pihole/ - cp ${PI_HOLE_LOCAL_REPO}/advanced/index.js /var/www/html/pihole/ - cp ${PI_HOLE_LOCAL_REPO}/advanced/blockingpage.css /var/www/html/pihole + echo -n "::: Installing block page..." + install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ + echo " done!" fi else - echo "::: Creating directory for blocking page" + echo "::: Creating directory for blocking page" install -d /var/www/html/pihole install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ if [ -f /var/www/html/index.lighttpd.html ]; then From 615ca56ea3967e915fb38a660ef9fe336e056126 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:27:58 +0100 Subject: [PATCH 11/85] fix inteliJ IDEA complaints --- automated install/basic-install.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index d603585f..908902f3 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -875,13 +875,13 @@ installPiholeWeb() { if [ -d "/var/www/html/pihole" ]; then if [[ ${CUSTOMBLOCKPAGE} == false ]]; then echo -n "::: Installing block page..." - install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ + install -D ${PI_HOLE_LOCAL_REPO}/advanced/index.* /advanced/blockingpage.* /var/www/html/pihole/ echo " done!" fi else echo "::: Creating directory for blocking page" install -d /var/www/html/pihole - install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ + install -D ${PI_HOLE_LOCAL_REPO}/advanced/index.* /advanced/blockingpage.* /var/www/html/pihole/ if [ -f /var/www/html/index.lighttpd.html ]; then mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig else From 324d4433c3fc616ba25e9fe58e534e3bfc30e6f6 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:31:31 +0100 Subject: [PATCH 12/85] even further simplify --- automated install/basic-install.sh | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 908902f3..feeb2791 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -872,24 +872,20 @@ installPiholeWeb() { fi # Install the web interface echo ":::" - if [ -d "/var/www/html/pihole" ]; then - if [[ ${CUSTOMBLOCKPAGE} == false ]]; then - echo -n "::: Installing block page..." - install -D ${PI_HOLE_LOCAL_REPO}/advanced/index.* /advanced/blockingpage.* /var/www/html/pihole/ - echo " done!" - fi - else - echo "::: Creating directory for blocking page" + + if [[ ${CUSTOMBLOCKPAGE} == false ]]; then + echo -n "::: Installing block page..." install -d /var/www/html/pihole install -D ${PI_HOLE_LOCAL_REPO}/advanced/index.* /advanced/blockingpage.* /var/www/html/pihole/ - if [ -f /var/www/html/index.lighttpd.html ]; then - mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig - else - printf "\n:::\tNo default index.lighttpd.html file found... not backing up" - fi echo " done!" fi + if [ -f /var/www/html/index.lighttpd.html ]; then + mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig + else + printf "\n:::\tNo default index.lighttpd.html file found... not backing up" + fi + # Install Sudoer file echo ":::" echo -n "::: Installing sudoer file..." From 5b0927ca4b735a9f3b996ec38877df3a0852cf29 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:32:27 +0100 Subject: [PATCH 13/85] tidy up output --- automated install/basic-install.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index feeb2791..62130ca6 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -880,10 +880,12 @@ installPiholeWeb() { echo " done!" fi + echo -n "::: Backing up default lighttpd index page..." if [ -f /var/www/html/index.lighttpd.html ]; then mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig + echo " done!" else - printf "\n:::\tNo default index.lighttpd.html file found... not backing up" + echo " No default index.lighttpd.html file found... not backing up" fi # Install Sudoer file From 19fd25c7cd54b3cfc19ded79373869c9d035dbb4 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:40:10 +0100 Subject: [PATCH 14/85] revert line, looks tidyer --- automated install/basic-install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 62130ca6..516f8ebf 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -876,7 +876,7 @@ installPiholeWeb() { if [[ ${CUSTOMBLOCKPAGE} == false ]]; then echo -n "::: Installing block page..." install -d /var/www/html/pihole - install -D ${PI_HOLE_LOCAL_REPO}/advanced/index.* /advanced/blockingpage.* /var/www/html/pihole/ + install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ echo " done!" fi From 525a1228c3c999ffc4b0dfd523c0c8b9cf3cb784 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Fri, 5 May 2017 22:43:37 +0100 Subject: [PATCH 15/85] clarify --- automated install/basic-install.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 516f8ebf..df60e59f 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -878,6 +878,8 @@ installPiholeWeb() { install -d /var/www/html/pihole install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ echo " done!" + else + echo "::: Custom block page detected... not overwriting!" fi echo -n "::: Backing up default lighttpd index page..." From 89fd962615339336886e3b7ad543746cb6f7f790 Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Sat, 6 May 2017 11:45:31 +0100 Subject: [PATCH 16/85] Revert "Ensure any changes to blocking page are updated." --- automated install/basic-install.sh | 50 ++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 537da830..3ca90db6 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -35,7 +35,7 @@ IPV4_ADDRESS="" IPV6_ADDRESS="" QUERY_LOGGING=true INSTALL_WEB=true -CUSTOMBLOCKPAGE=false + # Find the rows and columns will default to 80x24 is it can not be detected screen_size=$(stty size 2>/dev/null || echo 24 80) @@ -866,28 +866,44 @@ CreateLogFile() { } installPiholeWeb() { - - if [ -f ${setupVars} ]; then - . ${setupVars} - fi # Install the web interface echo ":::" + echo "::: Installing pihole custom index page..." + if [ -d "/var/www/html/pihole" ]; then + if [ -f "/var/www/html/pihole/index.php" ]; then + echo "::: Existing index.php detected, not overwriting" + else + echo -n "::: index.php missing, replacing... " + cp ${PI_HOLE_LOCAL_REPO}/advanced/index.php /var/www/html/pihole/ + echo " done!" + fi - if [[ ${CUSTOMBLOCKPAGE} == false ]]; then - echo -n "::: Installing block page..." + if [ -f "/var/www/html/pihole/index.js" ]; then + echo "::: Existing index.js detected, not overwriting" + else + echo -n "::: index.js missing, replacing... " + cp ${PI_HOLE_LOCAL_REPO}/advanced/index.js /var/www/html/pihole/ + echo " done!" + fi + + if [ -f "/var/www/html/pihole/blockingpage.css" ]; then + echo "::: Existing blockingpage.css detected, not overwriting" + else + echo -n "::: blockingpage.css missing, replacing... " + cp ${PI_HOLE_LOCAL_REPO}/advanced/blockingpage.css /var/www/html/pihole + echo " done!" + fi + + else + echo "::: Creating directory for blocking page" install -d /var/www/html/pihole install -D ${PI_HOLE_LOCAL_REPO}/advanced/{index,blockingpage}.* /var/www/html/pihole/ + if [ -f /var/www/html/index.lighttpd.html ]; then + mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig + else + printf "\n:::\tNo default index.lighttpd.html file found... not backing up" + fi echo " done!" - else - echo "::: Custom block page detected... not overwriting!" - fi - - echo -n "::: Backing up default lighttpd index page..." - if [ -f /var/www/html/index.lighttpd.html ]; then - mv /var/www/html/index.lighttpd.html /var/www/html/index.lighttpd.orig - echo " done!" - else - echo " No default index.lighttpd.html file found... not backing up" fi # Install Sudoer file From dfc32b26a6ffa1bd2ea2feac4c46b2ed683df170 Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Tue, 9 May 2017 13:11:28 -0700 Subject: [PATCH 17/85] We test for dpkg lock on line 830 directly, no need for the check also in the template section. Signed-off-by: Dan Schaper --- automated install/basic-install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index cb5dd6fc..2e3410d7 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -86,7 +86,7 @@ if command -v apt-get &> /dev/null; then #Debian Family ############################################# PKG_MANAGER="apt-get" - UPDATE_PKG_CACHE="test_dpkg_lock; ${PKG_MANAGER} update" + UPDATE_PKG_CACHE="${PKG_MANAGER} update" PKG_INSTALL=(${PKG_MANAGER} --yes --no-install-recommends install) # grep -c will return 1 retVal on 0 matches, block this throwing the set -e with an OR TRUE PKG_COUNT="${PKG_MANAGER} -s -o Debug::NoLocking=true upgrade | grep -c ^Inst || true" From 03201e2f201420626c61a8d8890e7079c1e35ac6 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Wed, 10 May 2017 13:07:56 +1000 Subject: [PATCH 18/85] Display FTL version & version.sh rewrite While testing to make sure `pihole -v` would output `pihole-FTL version`, I noticed some options didn't work how I expected them to. For example, if I use `pihole -v -p`, I would expect to see the version output of Pi-hole Core. Instead, I'm informed that it's an invalid option. I've had the following things in mind while rewriting this: * I'm operating under the assumption that FTL is only installed if the Admin Console is (Line 113 exit 0) * I have modified the help text to only output with `pihole -v --help` * I have modified all output to be more similar to the output style of `grep` and `curl` (Ditching ":::") Testing output: ``` w3k@MCT:~$ pihole -v Pi-hole version is v3.0.1-14-ga928cd3 (Latest: v3.0.1) Admin Console version is v3.0-9-g3760482 (Latest: v3.0.1) FTL version is v2.6.2 (Latest: v2.6.2) w3k@MCT:~$ pihole -v -c Current Pi-hole version is v3.0.1-14-ga928cd3 Current Admin Console version is v3.0-9-g3760482 Current FTL version is v2.6.2 w3k@MCT:~$ pihole -v -l Latest Pi-hole version is v3.0.1 Latest Admin Console version is v3.0.1 Latest FTL version is v2.6.2 w3k@MCT:~$ pihole -v -p --hash Current Pi-hole hash is a928cd3 w3k@MCT:~$ pihole -v -a --hash Current Admin Console hash is 3760482 w3k@MCT:~$ pihole -v --help Usage: pihole -v [REPO | OPTION] [OPTION] Show Pi-hole, Web Admin & FTL versions w3k@MCT:~$ pihole -v -foo Invalid Option! ``` --- advanced/Scripts/version.sh | 127 +++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 53 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 7f96e29a..289e4d93 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -66,72 +66,93 @@ getRemoteVersion(){ return 0 } -#PHHASHLATEST=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/commits/master | \ -# grep sha | \ -# head -n1 | \ -# awk -F ' ' '{ print $2 }' | \ -# tr -cd '[[:alnum:]]._-') - -#WEBHASHLATEST=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/commits/master | \ -# grep sha | \ -# head -n1 | \ -# awk -F ' ' '{ print $2 }' | \ -# tr -cd '[[:alnum:]]._-') - - -normalOutput() { - echo "::: Pi-hole version is $(getLocalVersion "${PHGITDIR}") (Latest version is $(getRemoteVersion pi-hole))" - if [ -d "${WEBGITDIR}" ]; then - echo "::: Web-Admin version is $(getLocalVersion "${WEBGITDIR}") (Latest version is $(getRemoteVersion AdminLTE))" - fi +coreOutput() { + [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(getLocalVersion ${PHGITDIR})" + [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion pi-hole)" + [ "$1" = "--hash" ] && hash="$(getLocalHash ${PHGITDIR})" + + if [ -n "$current" -a -n "$latest" ]; then + str="Pi-hole version is $current (Latest: $latest)" + elif [ -n "$current" -a -z "$latest" ]; then + str="Current Pi-hole version is $current" + elif [ -z "$current" -a -n "$latest" ]; then + str="Latest Pi-hole version is $latest" + elif [ -n "$hash" ]; then + str="Current Pi-hole hash is $hash" + else + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 + fi + echo " $str" } webOutput() { - if [ -d "${WEBGITDIR}" ]; then - case "${1}" in - "-l" | "--latest" ) echo $(getRemoteVersion AdminLTE);; - "-c" | "--current" ) echo $(getLocalVersion "${WEBGITDIR}");; - "-h" | "--hash" ) echo $(getLocalHash "${WEBGITDIR}");; - * ) echo "::: Invalid Option!"; exit 1; - esac + [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(getLocalVersion ${WEBGITDIR})" + [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion AdminLTE)" + [ "$1" = "--hash" ] && hash="$(getLocalHash ${WEBGITDIR})" + [ ! -d "${WEBGITDIR}" ] && str="Web interface not installed!" + + if [ -n "$current" -a -n "$latest" ]; then + str="Admin Console version is $current (Latest: $latest)" + elif [ -n "$current" -a -z "$latest" ]; then + str="Current Admin Console version is $current" + elif [ -z "$current" -a -n "$latest" ]; then + str="Latest Admin Console version is $latest" + elif [ -n "$hash" ]; then + str="Current Admin Console hash is $hash" else - echo "::: Web interface not installed!"; exit 1; + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 fi + echo " $str" } -coreOutput() { - case "${1}" in - "-l" | "--latest" ) echo $(getRemoteVersion pi-hole);; - "-c" | "--current" ) echo $(getLocalVersion "${PHGITDIR}");; - "-h" | "--hash" ) echo $(getLocalHash "${PHGITDIR}");; - * ) echo "::: Invalid Option!"; exit 1; - esac +ftlOutput() { + [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(pihole-FTL version)" + [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion FTL)" + [ ! -d "${WEBGITDIR}" ] && exit 0 + + if [ -n "$current" -a -n "$latest" ]; then + str="FTL version is $current (Latest: $latest)" + elif [ -n "$current" -a -z "$latest" ]; then + str="Current FTL version is $current" + elif [ -z "$current" -a -n "$latest" ]; then + str="Latest FTL version is $latest" + else + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 + fi + echo " $str" +} + +defaultOutput() { + coreOutput "$1" + webOutput "$1" + ftlOutput "$1" } helpFunc() { - cat << EOM -::: -::: Show Pi-hole/Web Admin versions -::: -::: Usage: pihole -v [ -a | -p ] [ -l | -c ] -::: -::: Options: -::: -a, --admin Show both current and latest versions of web admin -::: -p, --pihole Show both current and latest versions of Pi-hole core files -::: -l, --latest (Only after -a | -p) Return only latest version -::: -c, --current (Only after -a | -p) Return only current version -::: -h, --help Show this help dialog -::: -EOM + echo "Usage: pihole -v [REPO | OPTION] [OPTION] +Show Pi-hole, Web Admin & FTL versions + +Repositories: + -a, --admin Show both current and latest versions of Web Admin + -f, --ftl Show both current and latest versions of FTL + -p, --pihole Show both current and latest versions of Pi-hole Core + +Options: + -c, --current (Only after -a | -p | -f) Return the current version + -l, --latest (Only after -a | -p | -f) Return the latest version + -h, --hash (Only after -a | -p) Return the current Github hash + --help Show this help dialog +" exit 0 } -if [[ $# = 0 ]]; then - normalOutput -fi - case "${1}" in "-a" | "--admin" ) shift; webOutput "$@";; - "-p" | "--pihole" ) shift; coreOutput "$@" ;; - "-h" | "--help" ) helpFunc;; + "-p" | "--pihole" ) shift; coreOutput "$@";; + "-f" | "--ftl" ) shift; ftlOutput "$@";; + "--help" ) helpFunc;; + * ) defaultOutput "$@";; esac From fe0a35cc7ab50f54f465b6571a3dcefa8f6f1472 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 08:30:49 +1000 Subject: [PATCH 19/85] Update -h to work as --hash Also provide error output as per https://github.com/pi-hole/pi-hole/pull/1447#issuecomment-300600093 --- advanced/Scripts/version.sh | 43 ++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 289e4d93..9b878c8e 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -69,8 +69,9 @@ getRemoteVersion(){ coreOutput() { [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(getLocalVersion ${PHGITDIR})" [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion pi-hole)" - [ "$1" = "--hash" ] && hash="$(getLocalHash ${PHGITDIR})" - + [ "$1" = "-h" -o "$1" = "--hash" ] && hash="$(getLocalHash ${PHGITDIR})" + [ -n "$2" ] && error="true" + if [ -n "$current" -a -n "$latest" ]; then str="Pi-hole version is $current (Latest: $latest)" elif [ -n "$current" -a -z "$latest" ]; then @@ -80,17 +81,24 @@ coreOutput() { elif [ -n "$hash" ]; then str="Current Pi-hole hash is $hash" else - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 + error="true" fi + + if [ "$error" = "true" ]; then + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 + fi + echo " $str" } webOutput() { [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(getLocalVersion ${WEBGITDIR})" [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion AdminLTE)" - [ "$1" = "--hash" ] && hash="$(getLocalHash ${WEBGITDIR})" + [ "$1" = "-h" -o "$1" = "--hash" ] && hash="$(getLocalHash ${WEBGITDIR})" [ ! -d "${WEBGITDIR}" ] && str="Web interface not installed!" + [ -n "$2" ] && error="true" + if [ -n "$current" -a -n "$latest" ]; then str="Admin Console version is $current (Latest: $latest)" @@ -101,9 +109,14 @@ webOutput() { elif [ -n "$hash" ]; then str="Current Admin Console hash is $hash" else - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 + error="true" fi + + if [ "$error" = "true" ]; then + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 + fi + echo " $str" } @@ -111,6 +124,7 @@ ftlOutput() { [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(pihole-FTL version)" [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion FTL)" [ ! -d "${WEBGITDIR}" ] && exit 0 + [ -n "$2" ] && error="true" if [ -n "$current" -a -n "$latest" ]; then str="FTL version is $current (Latest: $latest)" @@ -119,16 +133,21 @@ ftlOutput() { elif [ -z "$current" -a -n "$latest" ]; then str="Latest FTL version is $latest" else - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 + error="true" fi + + if [ "$error" = "true" ]; then + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 + fi + echo " $str" } defaultOutput() { - coreOutput "$1" - webOutput "$1" - ftlOutput "$1" + coreOutput "$1" "$2" + webOutput "$1" "$2" + ftlOutput "$1" "$2" } helpFunc() { From 3081c151bd1e88d12ef527d40075cbfc7a18d890 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 09:13:32 +1000 Subject: [PATCH 20/85] Perform EXACT searches on HOSTS lists correctly `\s` on the end may be overkill, but it is the existing scanList() behaviour. --- pihole | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pihole b/pihole index eaf4e955..6bd5fb1f 100755 --- a/pihole +++ b/pihole @@ -86,7 +86,7 @@ scanList(){ method="${3}" if [[ ${method} == "-exact" ]]; then - grep -i -E -l "(^|\/)${domain}($|\/)" ${list} + grep -i -E -l "(^|\s|\/)${domain}($|\s|\/)" ${list} else grep -i "${domain}" ${list} fi From 7fef1fdc831db0c3bafba4c53a888cc492c63c87 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 10:11:04 +1000 Subject: [PATCH 21/85] Fixed indentation --- advanced/Scripts/version.sh | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 9b878c8e..62106342 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -81,12 +81,12 @@ coreOutput() { elif [ -n "$hash" ]; then str="Current Pi-hole hash is $hash" else - error="true" + error="true" fi if [ "$error" = "true" ]; then - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 fi echo " $str" @@ -109,12 +109,12 @@ webOutput() { elif [ -n "$hash" ]; then str="Current Admin Console hash is $hash" else - error="true" + error="true" fi if [ "$error" = "true" ]; then - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 fi echo " $str" @@ -133,12 +133,12 @@ ftlOutput() { elif [ -z "$current" -a -n "$latest" ]; then str="Latest FTL version is $latest" else - error="true" + error="true" fi if [ "$error" = "true" ]; then - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 fi echo " $str" From 2863308090296a43ae69c7ecc4f1ef176b756090 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 13:34:58 +1000 Subject: [PATCH 22/85] Minimise string duplication & other minor changes Instead of duplicating output strings, rewrite core/web/ftlOutput() into one neat versionOutput(). --- advanced/Scripts/version.sh | 123 +++++++++++++----------------------- 1 file changed, 44 insertions(+), 79 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 62106342..8ab95367 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -10,10 +10,16 @@ # Variables DEFAULT="-1" -PHGITDIR="/etc/.pihole/" +COREGITDIR="/etc/.pihole/" WEBGITDIR="/var/www/html/admin/" getLocalVersion() { + # FTL requires a different method + if [ "$1" == "FTL" ]; then + echo $(pihole-FTL version) + return 0 + fi + # Get the tagged version of the local repository local directory="${1}" local version @@ -33,6 +39,12 @@ getLocalVersion() { } getLocalHash() { + # FTL hash is not applicable + if [ "$1" == "FTL" ]; then + echo "N/A" + return 0 + fi + # Get the short hash of the local repository local directory="${1}" local hash @@ -66,88 +78,41 @@ getRemoteVersion(){ return 0 } -coreOutput() { - [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(getLocalVersion ${PHGITDIR})" - [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion pi-hole)" - [ "$1" = "-h" -o "$1" = "--hash" ] && hash="$(getLocalHash ${PHGITDIR})" - [ -n "$2" ] && error="true" - - if [ -n "$current" -a -n "$latest" ]; then - str="Pi-hole version is $current (Latest: $latest)" - elif [ -n "$current" -a -z "$latest" ]; then - str="Current Pi-hole version is $current" - elif [ -z "$current" -a -n "$latest" ]; then - str="Latest Pi-hole version is $latest" - elif [ -n "$hash" ]; then - str="Current Pi-hole hash is $hash" - else - error="true" - fi - - if [ "$error" = "true" ]; then - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 - fi - - echo " $str" -} - -webOutput() { - [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(getLocalVersion ${WEBGITDIR})" - [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion AdminLTE)" - [ "$1" = "-h" -o "$1" = "--hash" ] && hash="$(getLocalHash ${WEBGITDIR})" - [ ! -d "${WEBGITDIR}" ] && str="Web interface not installed!" - [ -n "$2" ] && error="true" - +versionOutput() { + [ "$1" == "pi-hole" ] && GITDIR=${COREGITDIR} + [ "$1" == "AdminLTE" ] && GITDIR=${WEBGITDIR} + [ "$1" == "FTL" ] && GITDIR="FTL" + [ "$2" == "-c" -o "$2" == "--current" -o -z "$2" ] && current=$(getLocalVersion $GITDIR) + [ "$2" == "-l" -o "$2" == "--latest" -o -z "$2" ] && latest=$(getRemoteVersion $1) + [ "$2" == "-h" -o "$2" == "--hash" ] && hash=$(getLocalHash $GITDIR) + if [ -n "$current" -a -n "$latest" ]; then - str="Admin Console version is $current (Latest: $latest)" + output="${1^} version is $current (Latest: $latest)" elif [ -n "$current" -a -z "$latest" ]; then - str="Current Admin Console version is $current" + output="Current ${1^} version is $current" elif [ -z "$current" -a -n "$latest" ]; then - str="Latest Admin Console version is $latest" + output="Latest ${1^} version is $latest" + elif [ "$hash" == "N/A" ]; then + output="" elif [ -n "$hash" ]; then - str="Current Admin Console hash is $hash" + output="Current ${1^} hash is $hash" else - error="true" + errorOutput fi - if [ "$error" = "true" ]; then - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 - fi - - echo " $str" + [ -n "$output" ] && echo " $output" } -ftlOutput() { - [ "$1" = "-c" -o "$1" = "--current" -o -z "$1" ] && current="$(pihole-FTL version)" - [ "$1" = "-l" -o "$1" = "--latest" -o -z "$1" ] && latest="$(getRemoteVersion FTL)" - [ ! -d "${WEBGITDIR}" ] && exit 0 - [ -n "$2" ] && error="true" - - if [ -n "$current" -a -n "$latest" ]; then - str="FTL version is $current (Latest: $latest)" - elif [ -n "$current" -a -z "$latest" ]; then - str="Current FTL version is $current" - elif [ -z "$current" -a -n "$latest" ]; then - str="Latest FTL version is $latest" - else - error="true" - fi - - if [ "$error" = "true" ]; then - echo " Invalid Option! Try 'pihole -v --help' for more information." - exit 1 - fi - - echo " $str" +errorOutput() { + echo " Invalid Option! Try 'pihole -v --help' for more information." + exit 1 } defaultOutput() { - coreOutput "$1" "$2" - webOutput "$1" "$2" - ftlOutput "$1" "$2" + versionOutput "pi-hole" "$@" + versionOutput "AdminLTE" "$@" + versionOutput "FTL" "$@" } helpFunc() { @@ -155,23 +120,23 @@ helpFunc() { Show Pi-hole, Web Admin & FTL versions Repositories: - -a, --admin Show both current and latest versions of Web Admin - -f, --ftl Show both current and latest versions of FTL - -p, --pihole Show both current and latest versions of Pi-hole Core + -p, --pihole Only retrieve info regarding Pi-hole repository + -a, --admin Only retrieve info regarding AdminLTE repository + -f, --ftl Only retrieve info regarding FTL repository Options: - -c, --current (Only after -a | -p | -f) Return the current version - -l, --latest (Only after -a | -p | -f) Return the latest version - -h, --hash (Only after -a | -p) Return the current Github hash + -c, --current Return the current version + -l, --latest Return the latest version + -h, --hash Return the Github hash from your local repositories --help Show this help dialog " exit 0 } case "${1}" in - "-a" | "--admin" ) shift; webOutput "$@";; - "-p" | "--pihole" ) shift; coreOutput "$@";; - "-f" | "--ftl" ) shift; ftlOutput "$@";; + "-p" | "--pihole" ) shift; versionOutput "pi-hole" "$@";; + "-a" | "--admin" ) shift; versionOutput "AdminLTE" "$@";; + "-f" | "--ftl" ) shift; versionOutput "FTL" "$@";; "--help" ) helpFunc;; * ) defaultOutput "$@";; esac From c6596f2c5481d5d266b0bb25db2e9b38dff9f6da Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 14:19:13 +1000 Subject: [PATCH 23/85] Modified syntax to be valid for Shellcheck --- advanced/Scripts/version.sh | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 8ab95367..923d86d8 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -16,7 +16,7 @@ WEBGITDIR="/var/www/html/admin/" getLocalVersion() { # FTL requires a different method if [ "$1" == "FTL" ]; then - echo $(pihole-FTL version) + pihole-FTL version return 0 fi @@ -25,8 +25,7 @@ getLocalVersion() { local version cd "${directory}" || { echo "${DEFAULT}"; return 1; } - version=$(git describe --tags --always || \ - echo "${DEFAULT}") + version=$(git describe --tags --always || echo "$DEFAULT") if [[ "${version}" =~ ^v ]]; then echo "${version}" elif [[ "${version}" == "${DEFAULT}" ]]; then @@ -50,8 +49,7 @@ getLocalHash() { local hash cd "${directory}" || { echo "${DEFAULT}"; return 1; } - hash=$(git rev-parse --short HEAD || \ - echo "${DEFAULT}") + hash=$(git rev-parse --short HEAD || echo "$DEFAULT") if [[ "${hash}" == "${DEFAULT}" ]]; then echo "ERROR" return 1 @@ -66,7 +64,7 @@ getRemoteVersion(){ local daemon="${1}" local version - version=$(curl --silent --fail https://api.github.com/repos/pi-hole/${daemon}/releases/latest | \ + version=$(curl --silent --fail "https://api.github.com/repos/pi-hole/${daemon}/releases/latest" | \ awk -F: '$1 ~/tag_name/ { print $2 }' | \ tr -cd '[[:alnum:]]._-') if [[ "${version}" =~ ^v ]]; then @@ -79,19 +77,19 @@ getRemoteVersion(){ } versionOutput() { - [ "$1" == "pi-hole" ] && GITDIR=${COREGITDIR} - [ "$1" == "AdminLTE" ] && GITDIR=${WEBGITDIR} + [ "$1" == "pi-hole" ] && GITDIR=$COREGITDIR + [ "$1" == "AdminLTE" ] && GITDIR=$WEBGITDIR [ "$1" == "FTL" ] && GITDIR="FTL" - [ "$2" == "-c" -o "$2" == "--current" -o -z "$2" ] && current=$(getLocalVersion $GITDIR) - [ "$2" == "-l" -o "$2" == "--latest" -o -z "$2" ] && latest=$(getRemoteVersion $1) - [ "$2" == "-h" -o "$2" == "--hash" ] && hash=$(getLocalHash $GITDIR) + [ "$2" == "-c" ] || [ "$2" == "--current" ] || [ -z "$2" ] && current=$(getLocalVersion $GITDIR) + [ "$2" == "-l" ] || [ "$2" == "--latest" ] || [ -z "$2" ] && latest=$(getRemoteVersion "$1") + [ "$2" == "-h" ] || [ "$2" == "--hash" ] && hash=$(getLocalHash "$GITDIR") - if [ -n "$current" -a -n "$latest" ]; then + if [ -n "$current" ] && [ -n "$latest" ]; then output="${1^} version is $current (Latest: $latest)" - elif [ -n "$current" -a -z "$latest" ]; then + elif [ -n "$current" ] && [ -z "$latest" ]; then output="Current ${1^} version is $current" - elif [ -z "$current" -a -n "$latest" ]; then + elif [ -z "$current" ] && [ -n "$latest" ]; then output="Latest ${1^} version is $latest" elif [ "$hash" == "N/A" ]; then output="" From 501b26decdeff6ba2131bf85fadf243dde49f1b3 Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Wed, 10 May 2017 22:08:06 -0700 Subject: [PATCH 24/85] Log and echo gateway responses --- advanced/Scripts/piholeDebug.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/advanced/Scripts/piholeDebug.sh b/advanced/Scripts/piholeDebug.sh index 10dd1e8b..8020cc80 100755 --- a/advanced/Scripts/piholeDebug.sh +++ b/advanced/Scripts/piholeDebug.sh @@ -260,18 +260,18 @@ ip_ping_check() { if [[ -n ${ip_def_gateway} ]]; then echo -n "::: Pinging default IPv${protocol} gateway: " if ! ping_gateway="$(${cmd} -q -W 3 -c 3 -n ${ip_def_gateway} -I ${PIHOLE_INTERFACE} | tail -n 3)"; then - echo "Gateway did not respond." + log_echo "Gateway did not respond." return 1 else - echo "Gateway responded." + log_echo "Gateway responded." log_write "${ping_gateway}" fi echo -n "::: Pinging Internet via IPv${protocol}: " if ! ping_inet="$(${cmd} -q -W 3 -c 3 -n ${g_addr} -I ${PIHOLE_INTERFACE} | tail -n 3)"; then - echo "Query did not respond." + log_echo "Query did not respond." return 1 else - echo "Query responded." + log_echo "Query responded." log_write "${ping_inet}" fi else From 58353e28399c1e36568526475d71114558db392c Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 19:58:35 +1000 Subject: [PATCH 25/85] Update queryFunc() to search Whitelist If there is a match in Whitelist/Blacklist/Wildcards, `[ ! -t 1 ]` will cause the search to end if the terminal is closed when the script is called. This has the intended effect of allowing a user to search for a W/B/W domain (as well as all the adlists it's found in) using `pihole -q` via Terminal, but the script will stop searching after a W/B/W match when called by the block page. --- pihole | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pihole b/pihole index 6bd5fb1f..95dd7a1c 100755 --- a/pihole +++ b/pihole @@ -106,12 +106,12 @@ queryFunc() { domain="${2}" fi - # Scan Blacklist and Wildcards - lists="/etc/pihole/blacklist.txt $wildcardlist" + # Scan Whitelist, Blacklist and Wildcards + lists="/etc/pihole/whitelist.txt /etc/pihole/blacklist.txt $wildcardlist" result=$(scanList ${domain} "${lists}" ${method}) if [ -n "$result" ]; then echo "$result" - exit 0 + [ ! -t 1 ] && exit 0 fi # Scan Domains lists From c35c7b2cea71a629805e89803618ce754d058eba Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 11 May 2017 20:21:23 +1000 Subject: [PATCH 26/85] Wrap in double brackets --- pihole | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pihole b/pihole index 95dd7a1c..4fafe27a 100755 --- a/pihole +++ b/pihole @@ -111,7 +111,7 @@ queryFunc() { result=$(scanList ${domain} "${lists}" ${method}) if [ -n "$result" ]; then echo "$result" - [ ! -t 1 ] && exit 0 + [[ ! -t 1 ]] && exit 0 fi # Scan Domains lists From ea0a9ceb37d8d58ba19a1238cfd85de8844bfcf5 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Fri, 12 May 2017 15:25:01 +1000 Subject: [PATCH 27/85] Provide remote hashes for version.sh * Provide remote hashes for comparison * Use double braces for all conditions (for consistency) * Suppress potential "cd" error output * Provide "not applicable" output upon any hash request for FTL --- advanced/Scripts/version.sh | 66 ++++++++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 19 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 923d86d8..cd4054fb 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -15,7 +15,7 @@ WEBGITDIR="/var/www/html/admin/" getLocalVersion() { # FTL requires a different method - if [ "$1" == "FTL" ]; then + if [[ "$1" == "FTL" ]]; then pihole-FTL version return 0 fi @@ -24,7 +24,7 @@ getLocalVersion() { local directory="${1}" local version - cd "${directory}" || { echo "${DEFAULT}"; return 1; } + cd "${directory}" 2> /dev/null || { echo "${DEFAULT}"; return 1; } version=$(git describe --tags --always || echo "$DEFAULT") if [[ "${version}" =~ ^v ]]; then echo "${version}" @@ -38,8 +38,8 @@ getLocalVersion() { } getLocalHash() { - # FTL hash is not applicable - if [ "$1" == "FTL" ]; then + # Local FTL hash does not exist on filesystem + if [[ "$1" == "FTL" ]]; then echo "N/A" return 0 fi @@ -48,7 +48,7 @@ getLocalHash() { local directory="${1}" local hash - cd "${directory}" || { echo "${DEFAULT}"; return 1; } + cd "${directory}" 2> /dev/null || { echo "${DEFAULT}"; return 1; } hash=$(git rev-parse --short HEAD || echo "$DEFAULT") if [[ "${hash}" == "${DEFAULT}" ]]; then echo "ERROR" @@ -59,6 +59,27 @@ getLocalHash() { return 0 } +getRemoteHash(){ + # Remote FTL hash is not applicable + if [[ "$1" == "FTL" ]]; then + echo "N/A" + return 0 + fi + + local daemon="${1}" + local branch="${2}" + + hash=$(git ls-remote --heads "https://github.com/pi-hole/${daemon}" | \ + awk -v bra="$branch" '$0~bra {print substr($0,0,8);exit}') + if [[ -n "$hash" ]]; then + echo "$hash" + else + echo "ERROR" + return 1 + fi + return 0 +} + getRemoteVersion(){ # Get the version from the remote origin local daemon="${1}" @@ -77,29 +98,36 @@ getRemoteVersion(){ } versionOutput() { - [ "$1" == "pi-hole" ] && GITDIR=$COREGITDIR - [ "$1" == "AdminLTE" ] && GITDIR=$WEBGITDIR - [ "$1" == "FTL" ] && GITDIR="FTL" + [[ "$1" == "pi-hole" ]] && GITDIR=$COREGITDIR + [[ "$1" == "AdminLTE" ]] && GITDIR=$WEBGITDIR + [[ "$1" == "FTL" ]] && GITDIR="FTL" - [ "$2" == "-c" ] || [ "$2" == "--current" ] || [ -z "$2" ] && current=$(getLocalVersion $GITDIR) - [ "$2" == "-l" ] || [ "$2" == "--latest" ] || [ -z "$2" ] && latest=$(getRemoteVersion "$1") - [ "$2" == "-h" ] || [ "$2" == "--hash" ] && hash=$(getLocalHash "$GITDIR") + [[ "$2" == "-c" ]] || [[ "$2" == "--current" ]] || [[ -z "$2" ]] && current=$(getLocalVersion $GITDIR) + [[ "$2" == "-l" ]] || [[ "$2" == "--latest" ]] || [[ -z "$2" ]] && latest=$(getRemoteVersion "$1") + if [[ "$2" == "-h" ]] || [[ "$2" == "--hash" ]]; then + [[ "$3" == "-c" ]] || [[ "$3" == "--current" ]] || [[ -z "$3" ]] && curHash=$(getLocalHash "$GITDIR") + [[ "$3" == "-l" ]] || [[ "$3" == "--latest" ]] || [[ -z "$3" ]] && latHash=$(getRemoteHash "$1" "$(cd "$GITDIR" 2> /dev/null && git rev-parse --abbrev-ref HEAD)") + fi - if [ -n "$current" ] && [ -n "$latest" ]; then + if [[ -n "$current" ]] && [[ -n "$latest" ]]; then output="${1^} version is $current (Latest: $latest)" - elif [ -n "$current" ] && [ -z "$latest" ]; then + elif [[ -n "$current" ]] && [[ -z "$latest" ]]; then output="Current ${1^} version is $current" - elif [ -z "$current" ] && [ -n "$latest" ]; then + elif [[ -z "$current" ]] && [[ -n "$latest" ]]; then output="Latest ${1^} version is $latest" - elif [ "$hash" == "N/A" ]; then - output="" - elif [ -n "$hash" ]; then - output="Current ${1^} hash is $hash" + elif [[ "$curHash" == "N/A" ]] || [[ "$latHash" == "N/A" ]]; then + output="${1^} hash is not applicable" + elif [[ -n "$curHash" ]] && [[ -n "$latHash" ]]; then + output="${1^} hash is $curHash (Latest: $latHash)" + elif [[ -n "$curHash" ]] && [[ -z "$latHash" ]]; then + output="Current ${1^} hash is $curHash" + elif [[ -z "$curHash" ]] && [[ -n "$latHash" ]]; then + output="Latest ${1^} hash is $latHash" else errorOutput fi - [ -n "$output" ] && echo " $output" + [[ -n "$output" ]] && echo " $output" } errorOutput() { From 31d5a7ae9ea77e4174da0c1010c5538ef1ebeff9 Mon Sep 17 00:00:00 2001 From: 0412465564 Date: Fri, 12 May 2017 22:29:07 +0200 Subject: [PATCH 28/85] whitelist on website blocked doesnt work (#1452) Since Pi-hole redirects ad domains to itself, accessing the script via de.ign.com is the same as pi.hole in this case. The fix should be as simple as adding a / before admin on this line. --- advanced/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/advanced/index.php b/advanced/index.php index bfc44a1d..1dd5acc7 100644 --- a/advanced/index.php +++ b/advanced/index.php @@ -185,7 +185,7 @@ function add() { } $.ajax({ - url: "admin/scripts/pi-hole/php/add.php", + url: "/admin/scripts/pi-hole/php/add.php", method: "post", data: {"domain":domain.val(), "list":"white", "pw":pw.val()}, success: function(response) { From b166410cbf71f8ef1e9e5519f8f446a8b626b0e2 Mon Sep 17 00:00:00 2001 From: Hans Geiblinger Date: Fri, 12 May 2017 16:39:55 -0400 Subject: [PATCH 29/85] Solve piholeLogFlush.sh having to be issued 2 x to clear logs (#1460) Simplified the command -v syntax, and added a sleep 3 timer to the first execution of the log rotation. The second execution was being issued while the first was still running, thus it would fail and you would have to issue the "Flush Logs" command a second time. --- advanced/Scripts/piholeLogFlush.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/advanced/Scripts/piholeLogFlush.sh b/advanced/Scripts/piholeLogFlush.sh index fd66b255..8e4c8266 100755 --- a/advanced/Scripts/piholeLogFlush.sh +++ b/advanced/Scripts/piholeLogFlush.sh @@ -10,9 +10,9 @@ echo -n "::: Flushing /var/log/pihole.log ..." # Test if logrotate is available on this system -if command -v /usr/sbin/logrotate &> /dev/null; then +if command -v /usr/sbin/logrotate >/dev/null; then # Flush twice to move all data out of sight of FTL - /usr/sbin/logrotate --force /etc/pihole/logrotate + /usr/sbin/logrotate --force /etc/pihole/logrotate; sleep 3 /usr/sbin/logrotate --force /etc/pihole/logrotate else # Flush both pihole.log and pihole.log.1 (if existing) From 7abf3497304075ceafdc370429dada01ea81dfae Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 13 May 2017 21:08:21 +0200 Subject: [PATCH 30/85] Use `echo "ABC" | pihole tricorder` to upload to Pi-hole's medical tricorder. Uses SSL if available. --- pihole | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/pihole b/pihole index 4fafe27a..f24461d3 100755 --- a/pihole +++ b/pihole @@ -94,7 +94,7 @@ scanList(){ queryFunc() { method="${3}" - + # If domain contains non ASCII characters, convert domain to punycode if python exists # Cr: https://serverfault.com/a/335079 if [ -z "${2}" ]; then @@ -105,7 +105,7 @@ queryFunc() { else domain="${2}" fi - + # Scan Whitelist, Blacklist and Wildcards lists="/etc/pihole/whitelist.txt /etc/pihole/blacklist.txt $wildcardlist" result=$(scanList ${domain} "${lists}" ${method}) @@ -122,7 +122,7 @@ queryFunc() { [ -n "$method" ] && exact="exact " echo "::: No ${exact}results found for ${domain}" fi - + exit 0 } @@ -268,6 +268,14 @@ piholeCheckoutFunc() { checkout "$@" } +tricorderFunc() { + if command -v openssl &> /dev/null; then + openssl s_client -quiet -connect tricorder.pi-hole.net:9998 2> /dev/null < /dev/stdin + else + nc tricorder.pi-hole.net 9999 < /dev/stdin + fi +} + helpFunc() { cat << EOM ::: Control all Pi-hole specific functions @@ -302,6 +310,7 @@ helpFunc() { ::: 'pihole disable 5m' - will disable blocking for 5 minutes ::: restartdns Restart dnsmasq ::: checkout Check out different branches +::: tricorder Upload log to Pi-hole's medical tricorder (uses SSL when possible) EOM exit 0 } @@ -333,5 +342,6 @@ case "${1}" in "-a" | "admin" ) webpageFunc "$@";; "-t" | "tail" ) tailFunc;; "checkout" ) piholeCheckoutFunc "$@";; + "tricorder" ) tricorderFunc;; * ) helpFunc;; esac From 55f78e3b64470f82e088ecc714187ac5dd972456 Mon Sep 17 00:00:00 2001 From: Adam Hill Date: Sat, 13 May 2017 18:44:41 -0500 Subject: [PATCH 31/85] Update list.sh I believe this has feature parity with `sed /foo/ Id` but also supports busybox, and my alpine docker ;) --- advanced/Scripts/list.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index 537ebac3..52c4c569 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -157,8 +157,8 @@ RemoveDomain() { if [[ "${bool}" == true ]]; then # Remove it from the other one echo "::: Removing $1 from $list..." - # /I flag: search case-insensitive - sed -i "/${domain}/Id" "${list}" + # Busybox sed compatible case-insensitive domain removal + sed -i "$(grep -in "^${domain}$" ${list} | awk -F':' '{print $1}' | tr '\n' ',' | sed 's/,$/\n/')d" ${list} reload=true else if [[ "${verbose}" == true ]]; then @@ -174,8 +174,8 @@ RemoveDomain() { if [[ "${bool}" == true ]]; then # Remove it from the other one echo "::: Removing $1 from $list..." - # /I flag: search case-insensitive - sed -i "/address=\/${domain}/Id" "${list}" + # Busybox sed compatible case-insensitive domain removal + sed -i "$(grep -in "/${domain}/" ${list} | awk -F':' '{print $1}' | tr '\n' ',' | sed 's/,$/\n/')d" ${list} reload=true else if [[ "${verbose}" == true ]]; then From 25601b9fcc4a87220cbd641deaf2f079b71994ee Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Sat, 13 May 2017 17:49:58 -0700 Subject: [PATCH 32/85] Document `sed` substitution for user readability Comment the oneliner with explanations of what each step does. --- advanced/Scripts/list.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index 52c4c569..05806e46 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -158,6 +158,10 @@ RemoveDomain() { # Remove it from the other one echo "::: Removing $1 from $list..." # Busybox sed compatible case-insensitive domain removal + # grep case insensitive domain from list, print line numbers + # split on ':' with awk and print the line number + # For conditions with more than one match, substitute newline with ',' + # sed substitute final trailing ',' with newline sed -i "$(grep -in "^${domain}$" ${list} | awk -F':' '{print $1}' | tr '\n' ',' | sed 's/,$/\n/')d" ${list} reload=true else From b721ed49abaa7cacb743de5547199b3beb11cee4 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 14 May 2017 11:11:44 +1000 Subject: [PATCH 33/85] Update Help Output (#1467) * File consistency * Tabs to 2 spaces * Corrected indenting * Double braced conditionals * Quoted variables within conditionals * Standardise core help text * Added help text for disable command * Added help text for logging command * Clean up * Fixed certain new lines and spaces * Sync with development branch * Formatting consistency * Tabs to 2 spaces * Corrected indenting * Double braced conditionals * Quoted variables within conditionals * Fixed certain newlines and spaces * Admin help text * Added help text for interface command * Sync with development branch * Formatting consistency * Tabs to 2 spaces * Fixed some wording * Fixed certain spaces * Formatting consistency * Minor wording changes * Tabs to 2 spaces * Corrected indenting * Double braced conditionals * Quoted variables within conditionals * Fixed certain newlines and spaces * Blacklist help text * Formatting consistency * Tabs to 2 spaces * Corrected indenting * Cronometer help text * Formatting consistency * Fixed certain newlines and spaces * Corrected indenting * Checkout warning alteration * Add checkout help text * Corrected help output --- advanced/Scripts/chronometer.sh | 131 ++++++------ advanced/Scripts/list.sh | 313 ++++++++++++++--------------- advanced/Scripts/piholeCheckout.sh | 30 +-- advanced/Scripts/version.sh | 168 +++++++++------- advanced/Scripts/webpage.sh | 187 ++++++++--------- pihole | 250 ++++++++++++----------- 6 files changed, 547 insertions(+), 532 deletions(-) diff --git a/advanced/Scripts/chronometer.sh b/advanced/Scripts/chronometer.sh index 67ff495b..b5d54e5f 100755 --- a/advanced/Scripts/chronometer.sh +++ b/advanced/Scripts/chronometer.sh @@ -8,101 +8,98 @@ # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. -#Functions############################################################################################################## +# Functions piLog="/var/log/pihole.log" gravity="/etc/pihole/gravity.list" . /etc/pihole/setupVars.conf function GetFTLData { - # Open connection to FTL - exec 3<>/dev/tcp/localhost/"$(cat /var/run/pihole-FTL.port)" + # Open connection to FTL + exec 3<>/dev/tcp/localhost/"$(cat /var/run/pihole-FTL.port)" - # Test if connection is open - if { >&3; } 2> /dev/null; then - # Send command to FTL - echo -e ">$1" >&3 + # Test if connection is open + if { >&3; } 2> /dev/null; then + # Send command to FTL + echo -e ">$1" >&3 - # Read input + # Read input + read -r -t 1 LINE <&3 + until [ ! $? ] || [[ "$LINE" == *"EOM"* ]]; do + echo "$LINE" >&1 read -r -t 1 LINE <&3 - until [ ! $? ] || [[ "$LINE" == *"EOM"* ]]; do - echo "$LINE" >&1 - read -r -t 1 LINE <&3 - done + done - # Close connection - exec 3>&- - exec 3<&- - fi + # Close connection + exec 3>&- + exec 3<&- + fi } outputJSON() { - get_summary_data - echo "{\"domains_being_blocked\":${domains_being_blocked_raw},\"dns_queries_today\":${dns_queries_today_raw},\"ads_blocked_today\":${ads_blocked_today_raw},\"ads_percentage_today\":${ads_percentage_today_raw}}" + get_summary_data + echo "{\"domains_being_blocked\":${domains_being_blocked_raw},\"dns_queries_today\":${dns_queries_today_raw},\"ads_blocked_today\":${ads_blocked_today_raw},\"ads_percentage_today\":${ads_percentage_today_raw}}" } get_summary_data() { - local summary=$(GetFTLData "stats") - domains_being_blocked_raw=$(grep "domains_being_blocked" <<< "${summary}" | grep -Eo "[0-9]+$") - domains_being_blocked=$(printf "%'.f" ${domains_being_blocked_raw}) - dns_queries_today_raw=$(grep "dns_queries_today" <<< "$summary" | grep -Eo "[0-9]+$") - dns_queries_today=$(printf "%'.f" ${dns_queries_today_raw}) - ads_blocked_today_raw=$(grep "ads_blocked_today" <<< "$summary" | grep -Eo "[0-9]+$") - ads_blocked_today=$(printf "%'.f" ${ads_blocked_today_raw}) - ads_percentage_today_raw=$(grep "ads_percentage_today" <<< "$summary" | grep -Eo "[0-9.]+$") - LC_NUMERIC=C ads_percentage_today=$(printf "%'.f" ${ads_percentage_today_raw}) + local summary=$(GetFTLData "stats") + domains_being_blocked_raw=$(grep "domains_being_blocked" <<< "${summary}" | grep -Eo "[0-9]+$") + domains_being_blocked=$(printf "%'.f" ${domains_being_blocked_raw}) + dns_queries_today_raw=$(grep "dns_queries_today" <<< "$summary" | grep -Eo "[0-9]+$") + dns_queries_today=$(printf "%'.f" ${dns_queries_today_raw}) + ads_blocked_today_raw=$(grep "ads_blocked_today" <<< "$summary" | grep -Eo "[0-9]+$") + ads_blocked_today=$(printf "%'.f" ${ads_blocked_today_raw}) + ads_percentage_today_raw=$(grep "ads_percentage_today" <<< "$summary" | grep -Eo "[0-9.]+$") + LC_NUMERIC=C ads_percentage_today=$(printf "%'.f" ${ads_percentage_today_raw}) } normalChrono() { - for (( ; ; )); do - get_summary_data - domain=$(GetFTLData recentBlocked) - clear - # Displays a colorful Pi-hole logo - echo " ___ _ _ _" - echo "| _ (_)___| |_ ___| |___" - echo "| _/ |___| ' \/ _ \ / -_)" - echo "|_| |_| |_||_\___/_\___|" - echo "" - echo " ${IPV4_ADDRESS}" - echo "" - uptime | cut -d' ' -f11- - #uptime -p #Doesn't work on all versions of uptime - uptime | awk -F'( |,|:)+' '{if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes."}' - echo "-------------------------------" - echo "Recently blocked:" - echo " $domain" + for (( ; ; )); do + get_summary_data + domain=$(GetFTLData recentBlocked) + clear + # Displays a colorful Pi-hole logo + echo " ___ _ _ _" + echo "| _ (_)___| |_ ___| |___" + echo "| _/ |___| ' \/ _ \ / -_)" + echo "|_| |_| |_||_\___/_\___|" + echo "" + echo " ${IPV4_ADDRESS}" + echo "" + uptime | cut -d' ' -f11- + #uptime -p # Doesn't work on all versions of uptime + uptime | awk -F'( |,|:)+' '{if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes."}' + echo "-------------------------------" + echo "Recently blocked:" + echo " $domain" - echo "Blocking: ${domains_being_blocked}" - echo "Queries: ${dns_queries_today}" - echo "Pi-holed: ${ads_blocked_today} (${ads_percentage_today}%)" + echo "Blocking: ${domains_being_blocked}" + echo "Queries: ${dns_queries_today}" + echo "Pi-holed: ${ads_blocked_today} (${ads_percentage_today}%)" - sleep 5 - done + sleep 5 + done } displayHelp() { - cat << EOM -::: Displays stats about your piHole! -::: -::: Usage: sudo pihole -c [optional:-j] -::: Note: If no option is passed, then stats are displayed on screen, updated every 5 seconds -::: -::: Options: -::: -j, --json output stats as JSON formatted string -::: -h, --help display this help text -EOM - exit 0 + echo "Usage: pihole -c [options] +Example: 'pihole -c -j' +Calculates stats and displays to an LCD + +Options: + -j, --json Output stats as JSON formatted string + -h, --help Display this help text" + exit 0 } if [[ $# = 0 ]]; then - normalChrono + normalChrono fi for var in "$@"; do - case "$var" in - "-j" | "--json" ) outputJSON;; - "-h" | "--help" ) displayHelp;; - * ) exit 1;; - esac + case "$var" in + "-j" | "--json" ) outputJSON;; + "-h" | "--help" ) displayHelp;; + * ) exit 1;; + esac done diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index 537ebac3..14b18249 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -3,14 +3,12 @@ # (c) 2017 Pi-hole, LLC (https://pi-hole.net) # Network-wide ad blocking via your own hardware. # -# Whitelists and blacklists domains +# Whitelist and blacklist domains # # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. - - -#globals +# Globals basename=pihole piholeDir=/etc/${basename} whitelist=${piholeDir}/whitelist.txt @@ -27,122 +25,120 @@ listMain="" listAlt="" helpFunc() { + if [[ "${listMain}" == "${whitelist}" ]]; then + letter="w" + word="white" + else + letter="b" + word="black" + fi - if [[ ${listMain} == ${whitelist} ]]; then - letter="w" - word="white" - else - letter="b" - word="black" - fi + echo "Usage: pihole -${letter} [options] +Example: 'pihole -${letter} site.com', or 'pihole -${letter} site1.com site2.com' +${word^}list one or more domains - cat << EOM -::: Immediately ${word}lists one or more domains in the hosts file -::: -::: Usage: pihole -${letter} domain1 [domain2 ...] -::: -::: Options: -::: -d, --delmode Remove domains from the ${word}list -::: -nr, --noreload Update ${word}list without refreshing dnsmasq -::: -q, --quiet Output is less verbose -::: -h, --help Show this help dialog -::: -l, --list Display your ${word}listed domains -EOM -if [[ "${letter}" == "b" ]]; then - echo "::: -wild, --wildcard Add wildcard entry (only blacklist)" -fi - exit 0 +Options:" + + if [[ "${letter}" == "b" ]]; then + echo " -wild, --wildcard Add wildcard entry to blacklist" + fi + +echo " -d, --delmode Remove domain(s) from the ${word}list + -nr, --noreload Update ${word}list without refreshing dnsmasq + -q, --quiet Make output less verbose + -h, --help Show this help dialog + -l, --list Display all your ${word}listed domains" + +exit 0 } EscapeRegexp() { - # This way we may safely insert an arbitrary - # string in our regular expressions - # Also remove leading "." if present - echo $* | sed 's/^\.*//' | sed "s/[]\.|$(){}?+*^]/\\\\&/g" | sed "s/\\//\\\\\//g" + # This way we may safely insert an arbitrary + # string in our regular expressions + # Also remove leading "." if present + echo $* | sed 's/^\.*//' | sed "s/[]\.|$(){}?+*^]/\\\\&/g" | sed "s/\\//\\\\\//g" } -HandleOther(){ - # First, convert everything to lowercase - domain=$(sed -e "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/" <<< "$1") +HandleOther() { + # First, convert everything to lowercase + domain=$(sed -e "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/" <<< "$1") - #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}/') - if [ -z "${validDomain}" ]; then - echo "::: $1 is not a valid argument or domain name" - else - domList=("${domList[@]}" ${validDomain}) - fi + # 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}/') + if [[ -z "${validDomain}" ]]; then + echo "::: $1 is not a valid argument or domain name" + else + domList=("${domList[@]}" ${validDomain}) + fi } PoplistFile() { - #check whitelist file exists, and if not, create it - if [[ ! -f ${whitelist} ]]; then - touch ${whitelist} - fi - for dom in "${domList[@]}"; do - # Logic : If addmode then add to desired list and remove from the other; if delmode then remove from desired list but do not add to the other - if ${addmode}; then - AddDomain "${dom}" "${listMain}" - RemoveDomain "${dom}" "${listAlt}" - if [[ "${listMain}" == "${whitelist}" || "${listMain}" == "${blacklist}" ]]; then - RemoveDomain "${dom}" "${wildcardlist}" - fi - else - RemoveDomain "${dom}" "${listMain}" - fi - done + # Check whitelist file exists, and if not, create it + if [[ ! -f ${whitelist} ]]; then + touch ${whitelist} + fi + + for dom in "${domList[@]}"; do + # Logic: If addmode then add to desired list and remove from the other; if delmode then remove from desired list but do not add to the other + if ${addmode}; then + AddDomain "${dom}" "${listMain}" + RemoveDomain "${dom}" "${listAlt}" + if [[ "${listMain}" == "${whitelist}" || "${listMain}" == "${blacklist}" ]]; then + RemoveDomain "${dom}" "${wildcardlist}" + fi + else + RemoveDomain "${dom}" "${listMain}" + fi + done } AddDomain() { - list="$2" - domain=$(EscapeRegexp "$1") + list="$2" + domain=$(EscapeRegexp "$1") - if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then + if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then + bool=true + # Is the domain in the list we want to add it to? + grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false - bool=true - #Is the domain in the list we want to add it to? - grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false + if [[ "${bool}" == false ]]; then + # Domain not found in the whitelist file, add it! + if [[ "${verbose}" == true ]]; then + echo "::: Adding $1 to $list..." + fi + reload=true + # Add it to the list we want to add it to + echo "$1" >> "${list}" + else + if [[ "${verbose}" == true ]]; then + echo "::: ${1} already exists in ${list}, no need to add!" + fi + fi + elif [[ "${list}" == "${wildcardlist}" ]]; then + source "${piholeDir}/setupVars.conf" + # Remove the /* from the end of the IPv4addr. + IPV4_ADDRESS=${IPV4_ADDRESS%/*} + IPV6_ADDRESS=${IPV6_ADDRESS} - if [[ "${bool}" == false ]]; then - #domain not found in the whitelist file, add it! - if [[ "${verbose}" == true ]]; then - echo "::: Adding $1 to $list..." - fi - reload=true - # Add it to the list we want to add it to - echo "$1" >> "${list}" - else - if [[ "${verbose}" == true ]]; then - echo "::: ${1} already exists in ${list}, no need to add!" - fi - fi + bool=true + # Is the domain in the list? + grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false - elif [[ "${list}" == "${wildcardlist}" ]]; then - - source "${piholeDir}/setupVars.conf" - #Remove the /* from the end of the IPv4addr. - IPV4_ADDRESS=${IPV4_ADDRESS%/*} - IPV6_ADDRESS=${IPV6_ADDRESS} - - bool=true - #Is the domain in the list? - grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false - - if [[ "${bool}" == false ]]; then - if [[ "${verbose}" == true ]]; then - echo "::: Adding $1 to wildcard blacklist..." - fi - reload=true - echo "address=/$1/${IPV4_ADDRESS}" >> "${wildcardlist}" - if [[ ${#IPV6_ADDRESS} > 0 ]] ; then - echo "address=/$1/${IPV6_ADDRESS}" >> "${wildcardlist}" - fi - else - if [[ "${verbose}" == true ]]; then - echo "::: ${1} already exists in wildcard blacklist, no need to add!" - fi - fi - fi + if [[ "${bool}" == false ]]; then + if [[ "${verbose}" == true ]]; then + echo "::: Adding $1 to wildcard blacklist..." + fi + reload=true + echo "address=/$1/${IPV4_ADDRESS}" >> "${wildcardlist}" + if [[ "${#IPV6_ADDRESS}" > 0 ]]; then + echo "address=/$1/${IPV6_ADDRESS}" >> "${wildcardlist}" + fi + else + if [[ "${verbose}" == true ]]; then + echo "::: ${1} already exists in wildcard blacklist, no need to add!" + fi + fi + fi } RemoveDomain() { @@ -150,85 +146,82 @@ RemoveDomain() { domain=$(EscapeRegexp "$1") if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then - - bool=true - #Is it in the list? Logic follows that if its whitelisted it should not be blacklisted and vice versa - grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false - if [[ "${bool}" == true ]]; then - # Remove it from the other one - echo "::: Removing $1 from $list..." - # /I flag: search case-insensitive - sed -i "/${domain}/Id" "${list}" - reload=true - else - if [[ "${verbose}" == true ]]; then - echo "::: ${1} does not exist in ${list}, no need to remove!" - fi + bool=true + # Is it in the list? Logic follows that if its whitelisted it should not be blacklisted and vice versa + grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false + if [[ "${bool}" == true ]]; then + # Remove it from the other one + echo "::: Removing $1 from $list..." + # /I flag: search case-insensitive + sed -i "/${domain}/Id" "${list}" + reload=true + else + if [[ "${verbose}" == true ]]; then + echo "::: ${1} does not exist in ${list}, no need to remove!" fi - + fi elif [[ "${list}" == "${wildcardlist}" ]]; then - - bool=true - #Is it in the list? - grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false - if [[ "${bool}" == true ]]; then - # Remove it from the other one - echo "::: Removing $1 from $list..." - # /I flag: search case-insensitive - sed -i "/address=\/${domain}/Id" "${list}" - reload=true - else - if [[ "${verbose}" == true ]]; then - echo "::: ${1} does not exist in ${list}, no need to remove!" - fi + bool=true + # Is it in the list? + grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false + if [[ "${bool}" == true ]]; then + # Remove it from the other one + echo "::: Removing $1 from $list..." + # /I flag: search case-insensitive + sed -i "/address=\/${domain}/Id" "${list}" + reload=true + else + if [[ "${verbose}" == true ]]; then + echo "::: ${1} does not exist in ${list}, no need to remove!" fi + fi fi } Reload() { - # Reload hosts file - pihole -g -sd + # Reload hosts file + pihole -g -sd } Displaylist() { - 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}" - exit 0; + 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}" + exit 0; } for var in "$@"; do - case "${var}" in - "-w" | "whitelist" ) listMain="${whitelist}"; listAlt="${blacklist}";; - "-b" | "blacklist" ) listMain="${blacklist}"; listAlt="${whitelist}";; - "-wild" | "wildcard" ) listMain="${wildcardlist}";; - "-nr"| "--noreload" ) reload=false;; - "-d" | "--delmode" ) addmode=false;; - "-f" | "--force" ) force=true;; - "-q" | "--quiet" ) verbose=false;; - "-h" | "--help" ) helpFunc;; - "-l" | "--list" ) Displaylist;; - * ) HandleOther "${var}";; - esac + case "${var}" in + "-w" | "whitelist" ) listMain="${whitelist}"; listAlt="${blacklist}";; + "-b" | "blacklist" ) listMain="${blacklist}"; listAlt="${whitelist}";; + "-wild" | "wildcard" ) listMain="${wildcardlist}";; + "-nr"| "--noreload" ) reload=false;; + "-d" | "--delmode" ) addmode=false;; + "-f" | "--force" ) force=true;; + "-q" | "--quiet" ) verbose=false;; + "-h" | "--help" ) helpFunc;; + "-l" | "--list" ) Displaylist;; + * ) HandleOther "${var}";; + esac done shift if [[ $# = 0 ]]; then - helpFunc + helpFunc fi PoplistFile if ${reload}; then - Reload + Reload fi diff --git a/advanced/Scripts/piholeCheckout.sh b/advanced/Scripts/piholeCheckout.sh index 09f20d6b..00bea12c 100644 --- a/advanced/Scripts/piholeCheckout.sh +++ b/advanced/Scripts/piholeCheckout.sh @@ -3,7 +3,7 @@ # (c) 2017 Pi-hole, LLC (https://pi-hole.net) # Network-wide ad blocking via your own hardware. # -# Checkout other branches than master +# Switch Pi-hole subsystems to a different Github branch # # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. @@ -18,9 +18,12 @@ PH_TEST="true" source "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh" # setupVars set in basic-install.sh source "${setupVars}" - update="false" +# Colour codes +red="\e[1;31m" +def="\e[0m" + fully_fetch_repo() { # Add upstream branches to shallow clone local directory="${1}" @@ -35,7 +38,7 @@ fully_fetch_repo() { return 0 } -get_available_branches(){ +get_available_branches() { # Return available branches local directory="${1}" @@ -79,23 +82,23 @@ checkout_pull_branch() { } warning1() { - echo "::: Note that changing the branch is a severe change of your Pi-hole system." - echo "::: This is not supported unless one of the developers explicitly asks you to do this!" - read -r -p "::: Have you read and understood this? [y/N] " response + 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 -e " ${red}This feature is NOT supported unless a Pi-hole developer explicitly asks!${def}" + read -r -p " Have you read and understood this? [Y/N] " response case ${response} in [yY][eE][sS]|[yY]) - echo "::: Continuing." + echo "::: Continuing with branch change." return 0 ;; *) - echo "::: Aborting." + echo "::: Branch change has been cancelled." return 1 ;; esac } -checkout() -{ +checkout() { local corebranches local webbranches @@ -192,11 +195,10 @@ checkout() if [[ ! "${1}" == "web" && "${update}" == "true" ]]; then echo "::: Running installer to upgrade your installation" if "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh" --unattended; then - exit 0 + exit 0 else - echo "Unable to complete update, contact Pi-hole" - exit 1 + echo "Unable to complete update, contact Pi-hole" + exit 1 fi fi } - diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 7f96e29a..73888295 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -3,24 +3,29 @@ # (c) 2017 Pi-hole, LLC (https://pi-hole.net) # Network-wide ad blocking via your own hardware. # -# shows version numbers +# Show version numbers # # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. # Variables DEFAULT="-1" -PHGITDIR="/etc/.pihole/" +COREGITDIR="/etc/.pihole/" WEBGITDIR="/var/www/html/admin/" getLocalVersion() { + # FTL requires a different method + if [[ "$1" == "FTL" ]]; then + pihole-FTL version + return 0 + fi + # Get the tagged version of the local repository local directory="${1}" local version - cd "${directory}" || { echo "${DEFAULT}"; return 1; } - version=$(git describe --tags --always || \ - echo "${DEFAULT}") + cd "${directory}" 2> /dev/null || { echo "${DEFAULT}"; return 1; } + version=$(git describe --tags --always || echo "$DEFAULT") if [[ "${version}" =~ ^v ]]; then echo "${version}" elif [[ "${version}" == "${DEFAULT}" ]]; then @@ -33,13 +38,18 @@ getLocalVersion() { } getLocalHash() { + # Local FTL hash does not exist on filesystem + if [[ "$1" == "FTL" ]]; then + echo "N/A" + return 0 + fi + # Get the short hash of the local repository local directory="${1}" local hash - cd "${directory}" || { echo "${DEFAULT}"; return 1; } - hash=$(git rev-parse --short HEAD || \ - echo "${DEFAULT}") + cd "${directory}" 2> /dev/null || { echo "${DEFAULT}"; return 1; } + hash=$(git rev-parse --short HEAD || echo "$DEFAULT") if [[ "${hash}" == "${DEFAULT}" ]]; then echo "ERROR" return 1 @@ -49,12 +59,33 @@ getLocalHash() { return 0 } +getRemoteHash(){ + # Remote FTL hash is not applicable + if [[ "$1" == "FTL" ]]; then + echo "N/A" + return 0 + fi + + local daemon="${1}" + local branch="${2}" + + hash=$(git ls-remote --heads "https://github.com/pi-hole/${daemon}" | \ + awk -v bra="$branch" '$0~bra {print substr($0,0,8);exit}') + if [[ -n "$hash" ]]; then + echo "$hash" + else + echo "ERROR" + return 1 + fi + return 0 +} + getRemoteVersion(){ # Get the version from the remote origin local daemon="${1}" local version - version=$(curl --silent --fail https://api.github.com/repos/pi-hole/${daemon}/releases/latest | \ + version=$(curl --silent --fail "https://api.github.com/repos/pi-hole/${daemon}/releases/latest" | \ awk -F: '$1 ~/tag_name/ { print $2 }' | \ tr -cd '[[:alnum:]]._-') if [[ "${version}" =~ ^v ]]; then @@ -66,72 +97,73 @@ getRemoteVersion(){ return 0 } -#PHHASHLATEST=$(curl -s https://api.github.com/repos/pi-hole/pi-hole/commits/master | \ -# grep sha | \ -# head -n1 | \ -# awk -F ' ' '{ print $2 }' | \ -# tr -cd '[[:alnum:]]._-') - -#WEBHASHLATEST=$(curl -s https://api.github.com/repos/pi-hole/AdminLTE/commits/master | \ -# grep sha | \ -# head -n1 | \ -# awk -F ' ' '{ print $2 }' | \ -# tr -cd '[[:alnum:]]._-') - - -normalOutput() { - echo "::: Pi-hole version is $(getLocalVersion "${PHGITDIR}") (Latest version is $(getRemoteVersion pi-hole))" - if [ -d "${WEBGITDIR}" ]; then - echo "::: Web-Admin version is $(getLocalVersion "${WEBGITDIR}") (Latest version is $(getRemoteVersion AdminLTE))" - fi -} - -webOutput() { - if [ -d "${WEBGITDIR}" ]; then - case "${1}" in - "-l" | "--latest" ) echo $(getRemoteVersion AdminLTE);; - "-c" | "--current" ) echo $(getLocalVersion "${WEBGITDIR}");; - "-h" | "--hash" ) echo $(getLocalHash "${WEBGITDIR}");; - * ) echo "::: Invalid Option!"; exit 1; - esac - else - echo "::: Web interface not installed!"; exit 1; +versionOutput() { + [[ "$1" == "pi-hole" ]] && GITDIR=$COREGITDIR + [[ "$1" == "AdminLTE" ]] && GITDIR=$WEBGITDIR + [[ "$1" == "FTL" ]] && GITDIR="FTL" + + [[ "$2" == "-c" ]] || [[ "$2" == "--current" ]] || [[ -z "$2" ]] && current=$(getLocalVersion $GITDIR) + [[ "$2" == "-l" ]] || [[ "$2" == "--latest" ]] || [[ -z "$2" ]] && latest=$(getRemoteVersion "$1") + if [[ "$2" == "-h" ]] || [[ "$2" == "--hash" ]]; then + [[ "$3" == "-c" ]] || [[ "$3" == "--current" ]] || [[ -z "$3" ]] && curHash=$(getLocalHash "$GITDIR") + [[ "$3" == "-l" ]] || [[ "$3" == "--latest" ]] || [[ -z "$3" ]] && latHash=$(getRemoteHash "$1" "$(cd "$GITDIR" 2> /dev/null && git rev-parse --abbrev-ref HEAD)") fi + + if [[ -n "$current" ]] && [[ -n "$latest" ]]; then + output="${1^} version is $current (Latest: $latest)" + elif [[ -n "$current" ]] && [[ -z "$latest" ]]; then + output="Current ${1^} version is $current" + elif [[ -z "$current" ]] && [[ -n "$latest" ]]; then + output="Latest ${1^} version is $latest" + elif [[ "$curHash" == "N/A" ]] || [[ "$latHash" == "N/A" ]]; then + output="${1^} hash is not applicable" + elif [[ -n "$curHash" ]] && [[ -n "$latHash" ]]; then + output="${1^} hash is $curHash (Latest: $latHash)" + elif [[ -n "$curHash" ]] && [[ -z "$latHash" ]]; then + output="Current ${1^} hash is $curHash" + elif [[ -z "$curHash" ]] && [[ -n "$latHash" ]]; then + output="Latest ${1^} hash is $latHash" + else + errorOutput + fi + + [[ -n "$output" ]] && echo "$output" } -coreOutput() { - case "${1}" in - "-l" | "--latest" ) echo $(getRemoteVersion pi-hole);; - "-c" | "--current" ) echo $(getLocalVersion "${PHGITDIR}");; - "-h" | "--hash" ) echo $(getLocalHash "${PHGITDIR}");; - * ) echo "::: Invalid Option!"; exit 1; - esac +errorOutput() { + echo "Invalid Option! Try 'pihole -v -h' for more information." + exit 1 +} + +defaultOutput() { + versionOutput "pi-hole" "$@" + versionOutput "AdminLTE" "$@" + versionOutput "FTL" "$@" } helpFunc() { - cat << EOM -::: -::: Show Pi-hole/Web Admin versions -::: -::: Usage: pihole -v [ -a | -p ] [ -l | -c ] -::: -::: Options: -::: -a, --admin Show both current and latest versions of web admin -::: -p, --pihole Show both current and latest versions of Pi-hole core files -::: -l, --latest (Only after -a | -p) Return only latest version -::: -c, --current (Only after -a | -p) Return only current version -::: -h, --help Show this help dialog -::: -EOM - exit 0 + echo "Usage: pihole -v [REPO | OPTION] [OPTION] +Example: 'pihole -v -p -l' +Show Pi-hole, Admin Console & FTL versions + +Repositories: + -p, --pihole Only retrieve info regarding Pi-hole repository + -a, --admin Only retrieve info regarding AdminLTE repository + -f, --ftl Only retrieve info regarding FTL repository + +Options: + -c, --current Return the current version + -l, --latest Return the latest version + -h, --hash Return the Github hash from your local repositories + --help Show this help dialog +" + exit 0 } -if [[ $# = 0 ]]; then - normalOutput -fi - case "${1}" in - "-a" | "--admin" ) shift; webOutput "$@";; - "-p" | "--pihole" ) shift; coreOutput "$@" ;; - "-h" | "--help" ) helpFunc;; + "-p" | "--pihole" ) shift; versionOutput "pi-hole" "$@";; + "-a" | "--admin" ) shift; versionOutput "AdminLTE" "$@";; + "-f" | "--ftl" ) shift; versionOutput "FTL" "$@";; + "--help" ) helpFunc;; + * ) defaultOutput "$@";; esac diff --git a/advanced/Scripts/webpage.sh b/advanced/Scripts/webpage.sh index d3ad3032..6626dab8 100755 --- a/advanced/Scripts/webpage.sh +++ b/advanced/Scripts/webpage.sh @@ -8,7 +8,6 @@ # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. - readonly setupVars="/etc/pihole/setupVars.conf" readonly dnsmasqconfig="/etc/dnsmasq.d/01-pihole.conf" readonly dhcpconfig="/etc/dnsmasq.d/02-pihole-dhcp.conf" @@ -16,23 +15,19 @@ readonly dhcpconfig="/etc/dnsmasq.d/02-pihole-dhcp.conf" readonly dhcpstaticconfig="/etc/dnsmasq.d/04-pihole-static-dhcp.conf" helpFunc() { - cat << EOM -::: Set admin options for the web interface of pihole -::: -::: Usage: pihole -a [options] -::: -::: Options: -::: -p, password Set web interface password, an empty input will remove any previously set password -::: -c, celsius Set Celsius temperature unit -::: -f, fahrenheit Set Fahrenheit temperature unit -::: -k, kelvin Set Kelvin temperature unit -::: -h, --help Show this help dialog -::: -i, interface Setup interface listening behavior of dnsmasq -::: pihole -a -i local : Listen on all interfaces, but allow only queries from -::: devices that are at most one hop away (local devices) -::: pihole -a -i single : Listen only on one interface (see PIHOLE_INTERFACE) -::: pihole -a -i all : Listen on all interfaces, permit all origins -EOM + echo "Usage: pihole -a [options] +Example: pihole -a -p password +Set options for the Admin Console + +Options: + -f, flush Flush the Pi-hole log + -p, password Set Admin Console password + -c, celsius Set Celsius as preferred temperature unit + -f, fahrenheit Set Fahrenheit as preferred temperature unit + -k, kelvin Set Kelvin as preferred temperature unit + -h, --help Show this help dialog + -i, interface Specify dnsmasq's interface listening behavior + Add '-h' for more info on interface usage" exit 0 } @@ -61,21 +56,18 @@ delete_dnsmasq_setting() { sed -i "/${1}/d" "${dnsmasqconfig}" } -SetTemperatureUnit(){ - +SetTemperatureUnit() { change_setting "TEMPERATUREUNIT" "${unit}" - } -HashPassword(){ - # Compute password hash twice to avoid rainbow table vulnerability - return=$(echo -n ${1} | sha256sum | sed 's/\s.*$//') - return=$(echo -n ${return} | sha256sum | sed 's/\s.*$//') - echo ${return} +HashPassword() { + # Compute password hash twice to avoid rainbow table vulnerability + return=$(echo -n ${1} | sha256sum | sed 's/\s.*$//') + return=$(echo -n ${return} | sha256sum | sed 's/\s.*$//') + echo ${return} } -SetWebPassword(){ - +SetWebPassword() { if [ "${SUDO_USER}" == "www-data" ]; then echo "Security measure: user www-data is not allowed to change webUI password!" echo "Exiting" @@ -175,8 +167,7 @@ trust-anchor=.,19036,8,2,49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE3 } -SetDNSServers(){ - +SetDNSServers() { # Save setting to file delete_setting "PIHOLE_DNS" IFS=',' read -r -a array <<< "${args[2]}" @@ -207,72 +198,59 @@ SetDNSServers(){ # Restart dnsmasq to load new configuration RestartDNS - } -SetExcludeDomains(){ - +SetExcludeDomains() { change_setting "API_EXCLUDE_DOMAINS" "${args[2]}" - } -SetExcludeClients(){ - +SetExcludeClients() { change_setting "API_EXCLUDE_CLIENTS" "${args[2]}" - } -Reboot(){ - +Reboot() { nohup bash -c "sleep 5; reboot" &> /dev/null /dev/null else service dnsmasq restart &> /dev/null fi - } -SetQueryLogOptions(){ - +SetQueryLogOptions() { change_setting "API_QUERY_LOG_SHOW" "${args[2]}" - } ProcessDHCPSettings() { - source "${setupVars}" if [[ "${DHCP_ACTIVE}" == "true" ]]; then + interface=$(grep 'PIHOLE_INTERFACE=' /etc/pihole/setupVars.conf | sed "s/.*=//") - interface=$(grep 'PIHOLE_INTERFACE=' /etc/pihole/setupVars.conf | sed "s/.*=//") + # Use eth0 as fallback interface + if [ -z ${interface} ]; then + interface="eth0" + fi - # Use eth0 as fallback interface - if [ -z ${interface} ]; then - interface="eth0" - fi + if [[ "${PIHOLE_DOMAIN}" == "" ]]; then + PIHOLE_DOMAIN="local" + change_setting "PIHOLE_DOMAIN" "${PIHOLE_DOMAIN}" + fi - if [[ "${PIHOLE_DOMAIN}" == "" ]]; then - PIHOLE_DOMAIN="local" - change_setting "PIHOLE_DOMAIN" "${PIHOLE_DOMAIN}" - fi + if [[ "${DHCP_LEASETIME}" == "0" ]]; then + leasetime="infinite" + elif [[ "${DHCP_LEASETIME}" == "" ]]; then + leasetime="24h" + change_setting "DHCP_LEASETIME" "${leasetime}" + else + leasetime="${DHCP_LEASETIME}h" + fi - if [[ "${DHCP_LEASETIME}" == "0" ]]; then - leasetime="infinite" - elif [[ "${DHCP_LEASETIME}" == "" ]]; then - leasetime="24h" - change_setting "DHCP_LEASETIME" "${leasetime}" - else - leasetime="${DHCP_LEASETIME}h" - fi - - # Write settings to file - echo "############################################################################### + # Write settings to file + echo "############################################################################### # DHCP SERVER CONFIG FILE AUTOMATICALLY POPULATED BY PI-HOLE WEB INTERFACE. # # ANY CHANGES MADE TO THIS FILE WILL BE LOST ON CHANGE # ############################################################################### @@ -283,26 +261,25 @@ dhcp-leasefile=/etc/pihole/dhcp.leases #quiet-dhcp " > "${dhcpconfig}" -if [[ "${PIHOLE_DOMAIN}" != "none" ]]; then - echo "domain=${PIHOLE_DOMAIN}" >> "${dhcpconfig}" -fi + if [[ "${PIHOLE_DOMAIN}" != "none" ]]; then + echo "domain=${PIHOLE_DOMAIN}" >> "${dhcpconfig}" + fi - if [[ "${DHCP_IPv6}" == "true" ]]; then -echo "#quiet-dhcp6 + if [[ "${DHCP_IPv6}" == "true" ]]; then + echo "#quiet-dhcp6 #enable-ra dhcp-option=option6:dns-server,[::] dhcp-range=::100,::1ff,constructor:${interface},ra-names,slaac,${leasetime} ra-param=*,0,0 " >> "${dhcpconfig}" - fi + fi else rm "${dhcpconfig}" &> /dev/null fi } -EnableDHCP(){ - +EnableDHCP() { change_setting "DHCP_ACTIVE" "true" change_setting "DHCP_START" "${args[2]}" change_setting "DHCP_END" "${args[3]}" @@ -320,8 +297,7 @@ EnableDHCP(){ RestartDNS } -DisableDHCP(){ - +DisableDHCP() { change_setting "DHCP_ACTIVE" "false" # Remove possible old setting from file @@ -333,23 +309,20 @@ DisableDHCP(){ RestartDNS } -SetWebUILayout(){ - +SetWebUILayout() { change_setting "WEBUIBOXEDLAYOUT" "${args[2]}" - } CustomizeAdLists() { - list="/etc/pihole/adlists.list" - if [[ "${args[2]}" == "enable" ]] ; then + if [[ "${args[2]}" == "enable" ]]; then sed -i "\\@${args[3]}@s/^#http/http/g" "${list}" - elif [[ "${args[2]}" == "disable" ]] ; then + elif [[ "${args[2]}" == "disable" ]]; then sed -i "\\@${args[3]}@s/^http/#http/g" "${list}" - elif [[ "${args[2]}" == "add" ]] ; then + elif [[ "${args[2]}" == "add" ]]; then echo "${args[3]}" >> ${list} - elif [[ "${args[2]}" == "del" ]] ; then + elif [[ "${args[2]}" == "del" ]]; then var=$(echo "${args[3]}" | sed 's/\//\\\//g') sed -i "/${var}/Id" "${list}" else @@ -358,18 +331,15 @@ CustomizeAdLists() { fi } -SetPrivacyMode(){ - - if [[ "${args[2]}" == "true" ]] ; then +SetPrivacyMode() { + if [[ "${args[2]}" == "true" ]]; then change_setting "API_PRIVACY_MODE" "true" else change_setting "API_PRIVACY_MODE" "false" fi - } ResolutionSettings() { - typ="${args[2]}" state="${args[3]}" @@ -378,11 +348,9 @@ ResolutionSettings() { elif [[ "${typ}" == "clients" ]]; then change_setting "API_GET_CLIENT_HOSTNAME" "${state}" fi - } AddDHCPStaticAddress() { - mac="${args[2]}" ip="${args[3]}" host="${args[4]}" @@ -397,18 +365,14 @@ AddDHCPStaticAddress() { # Full info given echo "dhcp-host=${mac},${ip},${host}" >> "${dhcpstaticconfig}" fi - } RemoveDHCPStaticAddress() { - mac="${args[2]}" sed -i "/dhcp-host=${mac}.*/d" "${dhcpstaticconfig}" - } -SetHostRecord(){ - +SetHostRecord() { if [ -n "${args[3]}" ]; then change_setting "HOSTRECORD" "${args[2]},${args[3]}" echo "Setting host record for ${args[2]} -> ${args[3]}" @@ -421,17 +385,28 @@ SetHostRecord(){ # Restart dnsmasq to load new configuration RestartDNS - } -SetListeningMode(){ - +SetListeningMode() { source "${setupVars}" + + if [[ "$3" == "-h" ]]; then + echo "Usage: pihole -a -i [interface] +Example: 'pihole -a -i local' +Specify dnsmasq's network interface listening behavior - if [[ "${args[2]}" == "all" ]] ; then +Interfaces: + local Listen on all interfaces, but only allow queries from + devices that are at most one hop away (local devices) + single Listen only on ${PIHOLE_INTERFACE} interface + all Listen on all interfaces, permit all origins" + exit 0 + fi + + if [[ "${args[2]}" == "all" ]]; then echo "Listening on all interfaces, permiting all origins, hope you have a firewall!" 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)" change_setting "DNSMASQ_LISTENING" "local" else @@ -446,17 +421,14 @@ SetListeningMode(){ # Restart dnsmasq to load new configuration RestartDNS fi - } -Teleporter() -{ +Teleporter() { local datetimestamp=$(date "+%Y-%m-%d_%H-%M-%S") php /var/www/html/admin/scripts/pi-hole/php/teleporter.php > "pi-hole-teleporter_${datetimestamp}.zip" } main() { - args=("$@") case "${args[1]}" in @@ -479,7 +451,7 @@ main() { "addstaticdhcp" ) AddDHCPStaticAddress;; "removestaticdhcp" ) RemoveDHCPStaticAddress;; "hostrecord" ) SetHostRecord;; - "-i" | "interface" ) SetListeningMode;; + "-i" | "interface" ) SetListeningMode "$@";; "-t" | "teleporter" ) Teleporter;; "adlist" ) CustomizeAdLists;; * ) helpFunc;; @@ -490,5 +462,4 @@ main() { if [[ $# = 0 ]]; then helpFunc fi - } diff --git a/pihole b/pihole index 83e13000..79a5c35d 100755 --- a/pihole +++ b/pihole @@ -9,11 +9,11 @@ # Please see LICENSE file for your rights under this license. readonly PI_HOLE_SCRIPT_DIR="/opt/pihole" - readonly wildcardlist="/etc/dnsmasq.d/03-pihole-wildcard.conf" + # Must be root to use this tool if [[ ! $EUID -eq 0 ]];then - if [ -x "$(command -v sudo)" ];then + if [[ -x "$(command -v sudo)" ]]; then exec sudo bash "$0" "$@" exit $? else @@ -80,66 +80,49 @@ updateGravityFunc() { exit 0 } -scanList(){ +scanList() { domain="${1}" list="${2}" method="${3}" - if [[ ${method} == "-exact" ]] ; then - grep -i -E "(^|\s)${domain}($|\s)" "${list}" - else - grep -i "${domain}" "${list}" - fi -} -processWildcards() { - IFS="." read -r -a array <<< "${1}" - for (( i=${#array[@]}-1; i>=0; i-- )); do - ar="" - for (( j=${#array[@]}-1; j>${#array[@]}-i-2; j-- )); do - if [[ $j == $((${#array[@]}-1)) ]]; then - ar="${array[$j]}" - else - ar="${array[$j]}.${ar}" - fi - done - echo "${ar}" - done + if [[ "${method}" == "-exact" ]]; then + grep -i -E -l "(^|\s|\/)${domain}($|\s|\/)" ${list} + else + grep -i "${domain}" ${list} + fi } queryFunc() { - domain="${2}" method="${3}" - lists=( /etc/pihole/list.* /etc/pihole/blacklist.txt) - for list in ${lists[@]}; do - if [ -e "${list}" ]; then - result=$(scanList ${domain} ${list} ${method}) - # Remove empty lines before couting number of results - count=$(sed '/^\s*$/d' <<< "$result" | wc -l) - echo "::: ${list} (${count} results)" - if [[ ${count} > 0 ]]; then - echo "${result}" - fi - echo "" - else - echo "::: ${list} does not exist" - echo "" - fi - done - - # Scan for possible wildcard matches - if [ -e "${wildcardlist}" ]; then - local wildcards=($(processWildcards "${domain}")) - for domain in ${wildcards[@]}; do - result=$(scanList "\/${domain}\/" ${wildcardlist}) - # Remove empty lines before couting number of results - count=$(sed '/^\s*$/d' <<< "$result" | wc -l) - if [[ ${count} > 0 ]]; then - echo "::: Wildcard blocking ${domain} (${count} results)" - echo "${result}" - echo "" - fi - done + + # If domain contains non ASCII characters, convert domain to punycode if python exists + # Cr: https://serverfault.com/a/335079 + if [[ -z "${2}" ]]; then + echo "::: No domain specified" + exit 1 + elif [[ "${2}" = *[![:ascii:]]* ]]; then + [[ "$(which python)" ]] && domain=$(python -c 'import sys;print sys.argv[1].decode("utf-8").encode("idna")' "${2}") + else + domain="${2}" fi + + # Scan Whitelist, Blacklist and Wildcards + lists="/etc/pihole/whitelist.txt /etc/pihole/blacklist.txt $wildcardlist" + result=$(scanList ${domain} "${lists}" ${method}) + if [[ -n "$result" ]]; then + echo "$result" + [[ ! -t 1 ]] && exit 0 + fi + + # Scan Domains lists + result=$(scanList ${domain} "/etc/pihole/*.domains" ${method}) + if [[ -n "$result" ]]; then + sort -t . -k 2 -g <<< "$result" + else + [ -n "$method" ] && exact="exact " + echo "::: No ${exact}results found for ${domain}" + fi + exit 0 } @@ -163,16 +146,16 @@ versionFunc() { restartDNS() { dnsmasqPid=$(pidof dnsmasq) - if [[ ${dnsmasqPid} ]]; then - # service already running - reload config - if [ -x "$(command -v systemctl)" ]; then + if [[ "${dnsmasqPid}" ]]; then + # Service already running - reload config + if [[ -x "$(command -v systemctl)" ]]; then systemctl restart dnsmasq else service dnsmasq restart fi else - # service not running, start it up - if [ -x "$(command -v systemctl)" ]; then + # Service not running, start it up + if [[ -x "$(command -v systemctl)" ]]; then systemctl start dnsmasq else service dnsmasq start @@ -181,16 +164,25 @@ restartDNS() { } piholeEnable() { - if [[ "${1}" == "0" ]] ; then - #Disable Pihole + if [[ "${2}" == "-h" ]]; then + echo "Usage: pihole disable [time] +Example: 'pihole disable', or 'pihole disable 5m' +Disable Pi-hole subsystems + +Time: + #s Disable Pi-hole functionality for # second(s) + #m Disable Pi-hole functionality for # minute(s)" + exit 0 + elif [[ "${1}" == "0" ]]; then + # Disable Pi-hole sed -i 's/^addn-hosts=\/etc\/pihole\/gravity.list/#addn-hosts=\/etc\/pihole\/gravity.list/' /etc/dnsmasq.d/01-pihole.conf echo "::: Blocking has been disabled!" - if [[ $# > 1 ]] ; then - if [[ ${2} == *"s"* ]] ; then + if [[ $# > 1 ]]; then + if [[ "${2}" == *"s"* ]]; then tt=${2%"s"} echo "::: Blocking will be re-enabled in ${tt} seconds" nohup bash -c "sleep ${tt}; pihole enable" /dev/null & - elif [[ ${2} == *"m"* ]] ; then + elif [[ "${2}" == *"m"* ]]; then tt=${2%"m"} echo "::: Blocking will be re-enabled in ${tt} minutes" tt=$((${tt}*60)) @@ -204,7 +196,7 @@ piholeEnable() { fi fi else - #Enable pihole + # Enable Pi-hole echo "::: Blocking has been enabled!" sed -i 's/^#addn-hosts/addn-hosts/' /etc/dnsmasq.d/01-pihole.conf fi @@ -213,15 +205,23 @@ piholeEnable() { piholeLogging() { shift + if [[ "${1}" == "-h" ]]; then + echo "Usage: pihole logging [options] +Example: 'pihole logging on' +Specify whether the Pi-hole log should be used - if [[ "${1}" == "off" ]] ; then - #Disable Logging +Options: + on Enable the Pi-hole log at /var/log/pihole.log + off Disable the Pi-hole log at /var/log/pihole.log" + exit 0 + elif [[ "${1}" == "off" ]]; then + # Disable logging 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 pihole -f echo "::: Logging has been disabled!" - elif [[ "${1}" == "on" ]] ; then - #Enable logging + elif [[ "${1}" == "on" ]]; then + # Enable logging 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 echo "::: Logging has been enabled!" @@ -233,12 +233,12 @@ piholeLogging() { } piholeStatus() { - if [[ $(netstat -plnt | grep -c ':53 ') > 0 ]]; then - if [[ "${1}" != "web" ]] ; then + if [[ "$(netstat -plnt | grep -c ':53 ')" -gt "0" ]]; then + if [[ "${1}" != "web" ]]; then echo "::: DNS service is running" fi else - if [[ "${1}" == "web" ]] ; then + if [[ "${1}" == "web" ]]; then echo "-1"; else echo "::: DNS service is NOT running" @@ -246,28 +246,28 @@ piholeStatus() { return fi - if [[ $(grep -i "^#addn-hosts=/" /etc/dnsmasq.d/01-pihole.conf) ]] ; then - #list is commented out - if [[ "${1}" == "web" ]] ; then + if [[ "$(grep -i "^#addn-hosts=/" /etc/dnsmasq.d/01-pihole.conf)" ]]; then + # List is commented out + if [[ "${1}" == "web" ]]; then echo 0; else echo "::: Pi-hole blocking is Disabled"; fi - elif [[ $(grep -i "^addn-hosts=/" /etc/dnsmasq.d/01-pihole.conf) ]] ; then - #list set - if [[ "${1}" == "web" ]] ; then + elif [[ "$(grep -i "^addn-hosts=/" /etc/dnsmasq.d/01-pihole.conf)" ]]; then + # List set + if [[ "${1}" == "web" ]]; then echo 1; else echo "::: Pi-hole blocking is Enabled"; fi else - #addn-host not found - if [[ "${1}" == "web" ]] ; then + # Addn-host not found + if [[ "${1}" == "web" ]]; then echo 99 else echo "::: No hosts file linked to dnsmasq, adding it in enabled state" fi - #add addn-host= to dnsmasq + # Add addn-host= to dnsmasq echo "addn-hosts=/etc/pihole/gravity.list" >> /etc/dnsmasq.d/01-pihole.conf restartDNS fi @@ -280,46 +280,66 @@ tailFunc() { } piholeCheckoutFunc() { + if [[ "$2" == "-h" ]]; then + echo "Usage: pihole checkout [repo] [branch] +Example: 'pihole checkout master' or 'pihole checkout core dev' +Switch Pi-hole subsystems to a different Github branch + +Repositories: + core [branch] Change the branch of Pi-hole's core subsystem + web [branch] Change the branch of Admin Console subsystem + +Branches: + master Update subsystems to the latest stable release + dev Update subsystems to the latest development release" + exit 0 + fi + source "${PI_HOLE_SCRIPT_DIR}"/piholeCheckout.sh shift checkout "$@" } helpFunc() { - cat << EOM -::: Control all Pi-hole specific functions -::: -::: Usage: pihole [options] -::: Add -h after -w (whitelist), -b (blacklist), -c (chronometer), or -a (admin) for more information on usage -::: -::: Options: -::: -w, whitelist Whitelist domain(s) -::: -b, blacklist Blacklist domain(s) (exact match) -::: -wild, wildcard Blacklist whole domain(s) (wildcard) -::: -d, debug Start a debugging session -::: Automated debugging can be enabled with '-a'. -::: 'pihole -d -a' -::: -f, flush Flush the 'pihole.log' file -::: -t, tail Output the last lines of the 'pihole.log' file. Lines are appended as the file grows -::: -up, updatePihole Update Pi-hole components -::: -r, reconfigure Reconfigure or Repair Pi-hole -::: -g, updateGravity Update the list of ad-serving domains -::: -c, chronometer Calculates stats and displays to an LCD -::: -h, help Show this help dialog -::: -v, version Show installed versions of Pi-hole and Web-Admin -::: -q, query Query the adlists for a specific domain -::: 'pihole -q domain -exact' shows exact matches only -::: -l, logging Enable or Disable logging (pass 'on' or 'off') -::: -a, admin Admin webpage options -::: uninstall Uninstall Pi-hole from your system! :( -::: status Display if Pi-hole is Enabled or Disabled -::: enable Enable Pi-hole DNS Blocking -::: disable Disable Pi-hole DNS Blocking -::: Blocking can also be disabled only temporarily, e.g., -::: 'pihole disable 5m' - will disable blocking for 5 minutes -::: restartdns Restart dnsmasq -::: checkout Check out different branches -EOM + echo "Usage: pihole [options] +Example: 'pihole -w -h' +Add '-h' after specific commands for more information on usage + +Whitelist/Blacklist Options: + -w, whitelist Whitelist domain(s) + -b, blacklist Blacklist domain(s) + -wild, wildcard Blacklist domain(s), and all its subdomains + Add '-h' for more info on whitelist/blacklist usage + +Debugging Options: + -d, debug Start a debugging session + Add '-a' to enable automated debugging + -f, flush Flush the Pi-hole log + -r, reconfigure Reconfigure or Repair Pi-hole subsystems + -t, tail View the live output of the Pi-hole log + +Options: + -a, admin Admin Console options + Add '-h' for more info on admin console usage + -c, chronometer Calculates stats and displays to an LCD + Add '-h' for more info on chronometer usage + -g, updateGravity Update the list of ad-serving domains + -h, --help, help Show this help dialog + -l, logging Specify whether the Pi-hole log should be used + Add '-h' for more info on logging usage + -q, query Query the adlists for a specified domain + Add '-exact' AFTER a specified domain for exact match + -up, updatePihole Update Pi-hole subsystems + -v, version Show installed versions of Pi-hole, Admin Console & FTL + Add '-h' for more info on version usage + uninstall Uninstall Pi-hole from your system + status Display the running status of Pi-hole subsystems + enable Enable Pi-hole subsystems + disable Disable Pi-hole subsystems + Add '-h' for more info on disable usage + restartdns Restart Pi-hole subsystems + checkout Switch Pi-hole subsystems to a different Github branch + Add '-h' for more info on checkout usage"; exit 0 } @@ -344,7 +364,7 @@ case "${1}" in "-l" | "logging" ) piholeLogging "$@";; "uninstall" ) uninstallFunc;; "enable" ) piholeEnable 1;; - "disable" ) piholeEnable 0 $2;; + "disable" ) piholeEnable 0 "$2";; "status" ) piholeStatus "$2";; "restartdns" ) restartDNS;; "-a" | "admin" ) webpageFunc "$@";; From 0e4473685bb9fdc00f196cf2751be99c6877368c Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 14 May 2017 11:47:56 +1000 Subject: [PATCH 34/85] Show help for "pihole -a -i --help" --- advanced/Scripts/webpage.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/advanced/Scripts/webpage.sh b/advanced/Scripts/webpage.sh index 6626dab8..8419aa8d 100755 --- a/advanced/Scripts/webpage.sh +++ b/advanced/Scripts/webpage.sh @@ -390,7 +390,7 @@ SetHostRecord() { SetListeningMode() { source "${setupVars}" - if [[ "$3" == "-h" ]]; then + if [[ "$3" == "-h" ]] || [[ "$3" == "--help" ]]; then echo "Usage: pihole -a -i [interface] Example: 'pihole -a -i local' Specify dnsmasq's network interface listening behavior From 4eb7d2868ca2d347ed0a497b6fb5c3a195ac4bf6 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 14 May 2017 11:53:40 +1000 Subject: [PATCH 35/85] Fix "pihole disable --help" and "pihole -l --help" --- pihole | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pihole b/pihole index 79a5c35d..1b75add5 100755 --- a/pihole +++ b/pihole @@ -164,7 +164,7 @@ restartDNS() { } piholeEnable() { - if [[ "${2}" == "-h" ]]; then + if [[ "${2}" == "-h" ]] || [[ "${2}" == "--help" ]]; then echo "Usage: pihole disable [time] Example: 'pihole disable', or 'pihole disable 5m' Disable Pi-hole subsystems @@ -205,7 +205,7 @@ Time: piholeLogging() { shift - if [[ "${1}" == "-h" ]]; then + if [[ "${1}" == "-h" ]] || [[ "${1}" == "--help" ]]; then echo "Usage: pihole logging [options] Example: 'pihole logging on' Specify whether the Pi-hole log should be used From 3bd677c102fddcce8ce72c81ae811b7453b8caa8 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 14 May 2017 11:57:46 +1000 Subject: [PATCH 36/85] Show help for "pihole -v -h" * Indent output text * Minor help text change --- advanced/Scripts/version.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/advanced/Scripts/version.sh b/advanced/Scripts/version.sh index 73888295..50bdb608 100755 --- a/advanced/Scripts/version.sh +++ b/advanced/Scripts/version.sh @@ -104,7 +104,7 @@ versionOutput() { [[ "$2" == "-c" ]] || [[ "$2" == "--current" ]] || [[ -z "$2" ]] && current=$(getLocalVersion $GITDIR) [[ "$2" == "-l" ]] || [[ "$2" == "--latest" ]] || [[ -z "$2" ]] && latest=$(getRemoteVersion "$1") - if [[ "$2" == "-h" ]] || [[ "$2" == "--hash" ]]; then + if [[ "$2" == "--hash" ]]; then [[ "$3" == "-c" ]] || [[ "$3" == "--current" ]] || [[ -z "$3" ]] && curHash=$(getLocalHash "$GITDIR") [[ "$3" == "-l" ]] || [[ "$3" == "--latest" ]] || [[ -z "$3" ]] && latHash=$(getRemoteHash "$1" "$(cd "$GITDIR" 2> /dev/null && git rev-parse --abbrev-ref HEAD)") fi @@ -127,11 +127,11 @@ versionOutput() { errorOutput fi - [[ -n "$output" ]] && echo "$output" + [[ -n "$output" ]] && echo " $output" } errorOutput() { - echo "Invalid Option! Try 'pihole -v -h' for more information." + echo " Invalid Option! Try 'pihole -v -h' for more information." exit 1 } @@ -142,7 +142,7 @@ defaultOutput() { } helpFunc() { - echo "Usage: pihole -v [REPO | OPTION] [OPTION] + echo "Usage: pihole -v [repo | option] [option] Example: 'pihole -v -p -l' Show Pi-hole, Admin Console & FTL versions @@ -154,8 +154,8 @@ Repositories: Options: -c, --current Return the current version -l, --latest Return the latest version - -h, --hash Return the Github hash from your local repositories - --help Show this help dialog + --hash Return the Github hash from your local repositories + -h, --help Show this help dialog " exit 0 } @@ -164,6 +164,6 @@ case "${1}" in "-p" | "--pihole" ) shift; versionOutput "pi-hole" "$@";; "-a" | "--admin" ) shift; versionOutput "AdminLTE" "$@";; "-f" | "--ftl" ) shift; versionOutput "FTL" "$@";; - "--help" ) helpFunc;; + "-h" | "--help" ) helpFunc;; * ) defaultOutput "$@";; esac From 39b74ebfd47e1847ebaff7cfabccb6fdc7d20f90 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 14 May 2017 12:22:19 +1000 Subject: [PATCH 37/85] Show help for "pihole checkout --help" --- pihole | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pihole b/pihole index 1b75add5..c1359ef9 100755 --- a/pihole +++ b/pihole @@ -280,7 +280,7 @@ tailFunc() { } piholeCheckoutFunc() { - if [[ "$2" == "-h" ]]; then + if [[ "$2" == "-h" ]] || [[ "$2" == "--help" ]]; then echo "Usage: pihole checkout [repo] [branch] Example: 'pihole checkout master' or 'pihole checkout core dev' Switch Pi-hole subsystems to a different Github branch From da9ff0cc66929401f82cd6db2536288a187f8021 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 14 May 2017 19:27:14 +1000 Subject: [PATCH 38/85] Tricorder: Insecure Opt-out * Check to see if Tricorder is being called directly * Provide opt-out for insecure transmission of debug log * Remove mention of internal function from help menu --- pihole | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/pihole b/pihole index f24461d3..8cffb5b2 100755 --- a/pihole +++ b/pihole @@ -269,10 +269,24 @@ piholeCheckoutFunc() { } tricorderFunc() { + if [ ! -p "/dev/stdin" ]; then + echo "Please do not call Tricorder directly." + exit 1 + fi + if command -v openssl &> /dev/null; then openssl s_client -quiet -connect tricorder.pi-hole.net:9998 2> /dev/null < /dev/stdin else - nc tricorder.pi-hole.net 9999 < /dev/stdin + echo "The debug log will be transmitted insecurely via plain-text" + echo "If you wish to cancel, press Ctrl-C to exit within 10 seconds" + secs="10" + while [ "$secs" -gt 0 ]; do + echo -ne "." + sleep 1 + : $((secs--)) + done + echo " " + nc tricorder.pi-hole.net 9999 < /dev/stdin < /dev/stdin fi } @@ -310,7 +324,6 @@ helpFunc() { ::: 'pihole disable 5m' - will disable blocking for 5 minutes ::: restartdns Restart dnsmasq ::: checkout Check out different branches -::: tricorder Upload log to Pi-hole's medical tricorder (uses SSL when possible) EOM exit 0 } From 69f361a3a1884879fe18ec8c1dccc09fabfc3815 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sun, 14 May 2017 16:28:35 +0200 Subject: [PATCH 39/85] :taco: is the new :shipit: squirrel --- .pullapprove.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pullapprove.yml b/.pullapprove.yml index 39566b34..188a64f2 100644 --- a/.pullapprove.yml +++ b/.pullapprove.yml @@ -10,7 +10,7 @@ group_defaults: reset_on_push: enabled: true reject_value: -2 - approve_regex: '^(Approved|:shipit:|:\+1:|Engage)' + approve_regex: '^(Approved|:shipit:|:\+1:|Engage|:taco:)' reject_regex: '^(Rejected|:-1:|Borg)' author_approval: auto: true From b9f2ba07173663d011f0bd4a2c2e7dea548ffac3 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Tue, 16 May 2017 09:48:46 +1000 Subject: [PATCH 40/85] Wording changes and bug fix --- pihole | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pihole b/pihole index 8cffb5b2..a630d67d 100755 --- a/pihole +++ b/pihole @@ -277,7 +277,8 @@ tricorderFunc() { if command -v openssl &> /dev/null; then openssl s_client -quiet -connect tricorder.pi-hole.net:9998 2> /dev/null < /dev/stdin else - echo "The debug log will be transmitted insecurely via plain-text" + echo "Your debug log will be transmitted unencrypted via plain-text" + echo "There is a possibility that this could be intercepted by a third party" echo "If you wish to cancel, press Ctrl-C to exit within 10 seconds" secs="10" while [ "$secs" -gt 0 ]; do @@ -286,7 +287,7 @@ tricorderFunc() { : $((secs--)) done echo " " - nc tricorder.pi-hole.net 9999 < /dev/stdin < /dev/stdin + nc tricorder.pi-hole.net 9999 < /dev/stdin fi } From 7453bf2ee62dfb9c79384ef43856a7446e4173da Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Tue, 16 May 2017 10:23:53 +1000 Subject: [PATCH 41/85] Fix wildcard help text * -wild is not a valid option since we're already using -wild --- advanced/Scripts/list.sh | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index 378d8402..308e1f5e 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -40,13 +40,8 @@ helpFunc() { Example: 'pihole -${param} site.com', or 'pihole -${param} site1.com site2.com' ${type^}list one or more domains -Options:" - - if [[ "${listMain}" == "${wildcardlist}" ]]; then - echo " -wild, --wildcard Block all subdomains of specified domain" - fi - -echo " -d, --delmode Remove domain(s) from the ${type}list +Options: + -d, --delmode Remove domain(s) from the ${type}list -nr, --noreload Update ${type}list without refreshing dnsmasq -q, --quiet Make output less verbose -h, --help Show this help dialog From 4e2c6a7b8e6e5825f6e609daf0694b483e27f55c Mon Sep 17 00:00:00 2001 From: DL6ER Date: Wed, 17 May 2017 12:44:35 +0200 Subject: [PATCH 42/85] Fix logrotation: manual flushing should be done twice, but automated rotation at midnight should only be done *once*! --- advanced/Scripts/piholeLogFlush.sh | 34 ++++++++++++++++++++++-------- advanced/pihole.cron | 2 +- pihole | 4 ++-- 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/advanced/Scripts/piholeLogFlush.sh b/advanced/Scripts/piholeLogFlush.sh index 8e4c8266..0a4d12bc 100755 --- a/advanced/Scripts/piholeLogFlush.sh +++ b/advanced/Scripts/piholeLogFlush.sh @@ -9,16 +9,32 @@ # Please see LICENSE file for your rights under this license. echo -n "::: Flushing /var/log/pihole.log ..." -# Test if logrotate is available on this system -if command -v /usr/sbin/logrotate >/dev/null; then - # Flush twice to move all data out of sight of FTL - /usr/sbin/logrotate --force /etc/pihole/logrotate; sleep 3 - /usr/sbin/logrotate --force /etc/pihole/logrotate +if [[ "$@" == *"once"* ]]; then + # Nightly logrotation + if command -v /usr/sbin/logrotate >/dev/null; then + # Logrotate once + /usr/sbin/logrotate --force /etc/pihole/logrotate + else + # Copy pihole.log over to pihole.log.1 + # and empty out pihole.log + # Note that moving the file is not an option, as + # dnsmasq would happily continue writing into the + # moved file (it will have the same file handler) + cp /var/log/pihole.log /var/log/pihole.log.1 + echo " " > /var/log/pihole.log + fi else - # Flush both pihole.log and pihole.log.1 (if existing) - echo " " > /var/log/pihole.log - if [ -f /var/log/pihole.log.1 ]; then - echo " " > /var/log/pihole.log.1 + # Manual flushing + if command -v /usr/sbin/logrotate >/dev/null; then + # Logrotate twice to move all data out of sight of FTL + /usr/sbin/logrotate --force /etc/pihole/logrotate; sleep 3 + /usr/sbin/logrotate --force /etc/pihole/logrotate + else + # Flush both pihole.log and pihole.log.1 (if existing) + echo " " > /var/log/pihole.log + if [ -f /var/log/pihole.log.1 ]; then + echo " " > /var/log/pihole.log.1 + fi fi fi echo "... done!" diff --git a/advanced/pihole.cron b/advanced/pihole.cron index c885b371..be35dc50 100644 --- a/advanced/pihole.cron +++ b/advanced/pihole.cron @@ -24,6 +24,6 @@ # Pi-hole: Flush the log daily at 00:00 so it doesn't get out of control # Stats will be viewable in the Web interface thanks to the cron job above # The flush script will use logrotate if available -00 00 * * * root PATH="$PATH:/usr/local/bin/" pihole flush +00 00 * * * root PATH="$PATH:/usr/local/bin/" pihole flush once @reboot root /usr/sbin/logrotate /etc/pihole/logrotate diff --git a/pihole b/pihole index feebbc1c..d116e248 100755 --- a/pihole +++ b/pihole @@ -61,7 +61,7 @@ debugFunc() { } flushFunc() { - "${PI_HOLE_SCRIPT_DIR}"/piholeLogFlush.sh + "${PI_HOLE_SCRIPT_DIR}"/piholeLogFlush.sh "$@" exit 0 } @@ -353,7 +353,7 @@ case "${1}" in "-b" | "blacklist" ) blacklistFunc "$@";; "-wild" | "wildcard" ) wildcardFunc "$@";; "-d" | "debug" ) debugFunc "$@";; - "-f" | "flush" ) flushFunc;; + "-f" | "flush" ) flushFunc "$@";; "-up" | "updatePihole" ) updatePiholeFunc;; "-r" | "reconfigure" ) reconfigurePiholeFunc;; "-g" | "updateGravity" ) updateGravityFunc "$@";; From c9042ffedd110485bd4e248fb2737a6c283fcc01 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Wed, 17 May 2017 12:51:04 +0200 Subject: [PATCH 43/85] Print echos only when manual flushing is requested --- advanced/Scripts/piholeLogFlush.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/advanced/Scripts/piholeLogFlush.sh b/advanced/Scripts/piholeLogFlush.sh index 0a4d12bc..9801d8ac 100755 --- a/advanced/Scripts/piholeLogFlush.sh +++ b/advanced/Scripts/piholeLogFlush.sh @@ -8,7 +8,6 @@ # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. -echo -n "::: Flushing /var/log/pihole.log ..." if [[ "$@" == *"once"* ]]; then # Nightly logrotation if command -v /usr/sbin/logrotate >/dev/null; then @@ -25,6 +24,7 @@ if [[ "$@" == *"once"* ]]; then fi else # Manual flushing + echo -n "::: Flushing /var/log/pihole.log ..." if command -v /usr/sbin/logrotate >/dev/null; then # Logrotate twice to move all data out of sight of FTL /usr/sbin/logrotate --force /etc/pihole/logrotate; sleep 3 @@ -36,5 +36,5 @@ else echo " " > /var/log/pihole.log.1 fi fi + echo "... done!" fi -echo "... done!" From 42eb811910ddb2fcd4a39a1a49b922686126ebce Mon Sep 17 00:00:00 2001 From: DL6ER Date: Wed, 17 May 2017 12:54:43 +0200 Subject: [PATCH 44/85] Add "quiet" mode + update comments in the cron file --- advanced/Scripts/piholeLogFlush.sh | 7 ++++++- advanced/pihole.cron | 7 ++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/advanced/Scripts/piholeLogFlush.sh b/advanced/Scripts/piholeLogFlush.sh index 9801d8ac..cc553b32 100755 --- a/advanced/Scripts/piholeLogFlush.sh +++ b/advanced/Scripts/piholeLogFlush.sh @@ -8,6 +8,9 @@ # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. +if [[ "$@" != *"quiet"* ]]; then + echo -n "::: Flushing /var/log/pihole.log ..." +fi if [[ "$@" == *"once"* ]]; then # Nightly logrotation if command -v /usr/sbin/logrotate >/dev/null; then @@ -24,7 +27,6 @@ if [[ "$@" == *"once"* ]]; then fi else # Manual flushing - echo -n "::: Flushing /var/log/pihole.log ..." if command -v /usr/sbin/logrotate >/dev/null; then # Logrotate twice to move all data out of sight of FTL /usr/sbin/logrotate --force /etc/pihole/logrotate; sleep 3 @@ -36,5 +38,8 @@ else echo " " > /var/log/pihole.log.1 fi fi +fi + +if [[ "$@" != *"quiet"* ]]; then echo "... done!" fi diff --git a/advanced/pihole.cron b/advanced/pihole.cron index be35dc50..f1beb08c 100644 --- a/advanced/pihole.cron +++ b/advanced/pihole.cron @@ -21,9 +21,10 @@ # Pi-hole: Update Pi-hole! Uncomment to enable auto update #30 2 * * 7 root PATH="$PATH:/usr/local/bin/" pihole updatePihole -# Pi-hole: Flush the log daily at 00:00 so it doesn't get out of control -# Stats will be viewable in the Web interface thanks to the cron job above +# Pi-hole: Flush the log daily at 00:00 # The flush script will use logrotate if available -00 00 * * * root PATH="$PATH:/usr/local/bin/" pihole flush once +# parameter "once": logrotate only once (default is twice) +# parameter "quiet": don't print messages +00 00 * * * root PATH="$PATH:/usr/local/bin/" pihole flush once quiet @reboot root /usr/sbin/logrotate /etc/pihole/logrotate From 1f3db8b6025e6f81b41d7d134ac07559ea6d8ead Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 18 May 2017 12:43:17 +1000 Subject: [PATCH 45/85] Confirm Tricorder is online * Scan port 9998 to confirm the availability of "tricorder.pi-hole.net" * Exit codes for upload process --- pihole | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pihole b/pihole index 11369ae1..3db64172 100755 --- a/pihole +++ b/pihole @@ -305,9 +305,15 @@ tricorderFunc() { echo "Please do not call Tricorder directly." exit 1 fi + + if ! timeout 2 nc -z tricorder.pi-hole.net 9998 &> /dev/null; then + echo "Unable to connect to Pi-hole's Tricorder server." + exit 1 + fi if command -v openssl &> /dev/null; then openssl s_client -quiet -connect tricorder.pi-hole.net:9998 2> /dev/null < /dev/stdin + exit "$?" else echo "Your debug log will be transmitted unencrypted via plain-text" echo "There is a possibility that this could be intercepted by a third party" @@ -320,6 +326,7 @@ tricorderFunc() { done echo " " nc tricorder.pi-hole.net 9999 < /dev/stdin + exit "$?" fi } From a620a5c430f34e0c4bcd4ae906ee60aa982520bd Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 18 May 2017 12:53:32 +1000 Subject: [PATCH 46/85] Formatting consistency --- pihole | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pihole b/pihole index 3db64172..869db5ba 100755 --- a/pihole +++ b/pihole @@ -301,7 +301,7 @@ Branches: } tricorderFunc() { - if [ ! -p "/dev/stdin" ]; then + if [[ ! -p "/dev/stdin" ]]; then echo "Please do not call Tricorder directly." exit 1 fi @@ -319,7 +319,7 @@ tricorderFunc() { echo "There is a possibility that this could be intercepted by a third party" echo "If you wish to cancel, press Ctrl-C to exit within 10 seconds" secs="10" - while [ "$secs" -gt 0 ]; do + while [[ "$secs" -gt "0" ]]; do echo -ne "." sleep 1 : $((secs--)) From 69b41dd72e19e7ed490ce7233638b04d5bc2f4bd Mon Sep 17 00:00:00 2001 From: Mcat12 Date: Fri, 19 May 2017 11:16:34 -0400 Subject: [PATCH 47/85] Add link to Windows DNS Swapper See #1400 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 75c548e5..6f8813fa 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ You can view [real-time stats](https://discourse.pi-hole.net/t/how-do-i-view-my- - [Let your blink1 device blink when Pi-hole filters ads](https://gist.github.com/elpatron68/ec0b4c582e5abf604885ac1e068d233f) - [Pi-hole Prometheus exporter](https://github.com/nlamirault/pihole_exporter): a [Prometheus](https://prometheus.io/) exporter for Pi-hole - [Pi-hole Droid - open source Android client](https://github.com/friimaind/pi-hole-droid) +- [Windows DNS Swapper](https://github.com/roots84/DNS-Swapper), see [#1400](https://github.com/pi-hole/pi-hole/issues/1400) ## Coverage From c655e6ea7343ffb1bce2f813c4e38f5c5fc6eac4 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 20 May 2017 15:47:51 +0200 Subject: [PATCH 48/85] Install loopback firewall rules for FTL (#1419) * Install loopback firewall rules for FTL * FirewallD FTL ports Signed-off-by: Dan Schaper * Remove firewallD FTL local rules. Local rules should not be blocked in firewallD, not requred for internal service FTD> * Reinstate https rules, and delete FTL rules Fixes earlier commit. --- automated install/basic-install.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 7d5a5d0e..a2aff252 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -980,6 +980,7 @@ configureFirewall() { iptables -C INPUT -p tcp -m tcp --dport 80 -j ACCEPT &> /dev/null || iptables -I INPUT 1 -p tcp -m tcp --dport 80 -j ACCEPT iptables -C INPUT -p tcp -m tcp --dport 53 -j ACCEPT &> /dev/null || iptables -I INPUT 1 -p tcp -m tcp --dport 53 -j ACCEPT iptables -C INPUT -p udp -m udp --dport 53 -j ACCEPT &> /dev/null || iptables -I INPUT 1 -p udp -m udp --dport 53 -j ACCEPT + iptables -C INPUT -p tcp -m tcp --dport 4711:4720 -i lo -j ACCEPT &> /dev/null || iptables -I INPUT 1 -p tcp -m tcp --dport 4711:4720 -i lo -j ACCEPT return 0 fi else From 2ef87ad110f849dce59a3f3dd336fb35e459ce5b Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Mon, 22 May 2017 06:47:26 +1000 Subject: [PATCH 49/85] Retrieve local repos on repair (#1481) * Retrieve local repos on repair * Change conditional to check for repair * Change wording of Update/Reconfigure message * Fixed indenting * Perform "git reset --hard" on reconfigure --- automated install/basic-install.sh | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index a2aff252..5d893067 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -1180,22 +1180,23 @@ update_dialogs() { } clone_or_update_repos() { -if [[ "${reconfigure}" == true ]]; then - echo "::: --reconfigure passed to install script. Not downloading/updating local repos" - else - # Get Git files for Core and Admin - getGitFiles ${PI_HOLE_LOCAL_REPO} ${piholeGitUrl} || \ - { echo "!!! Unable to clone ${piholeGitUrl} into ${PI_HOLE_LOCAL_REPO}, unable to continue."; \ - exit 1; \ - } + if [[ "${reconfigure}" == true ]]; then + echo "::: --reconfigure passed to install script. Resetting changes to local repos" + git reset --hard + else + # Get Git files for Core and Admin + getGitFiles ${PI_HOLE_LOCAL_REPO} ${piholeGitUrl} || \ + { echo "!!! Unable to clone ${piholeGitUrl} into ${PI_HOLE_LOCAL_REPO}, unable to continue."; \ + exit 1; \ + } - if [[ ${INSTALL_WEB} == true ]]; then - getGitFiles ${webInterfaceDir} ${webInterfaceGitUrl} || \ - { echo "!!! Unable to clone ${webInterfaceGitUrl} into ${webInterfaceDir}, unable to continue."; \ - exit 1; \ - } - fi + if [[ ${INSTALL_WEB} == true ]]; then + getGitFiles ${webInterfaceDir} ${webInterfaceGitUrl} || \ + { echo "!!! Unable to clone ${webInterfaceGitUrl} into ${webInterfaceDir}, unable to continue."; \ + exit 1; \ + } fi + fi } FTLinstall() { From 74eb8c8622ef701aad3d509bf88d9d7e3c6ceb40 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Mon, 22 May 2017 23:43:52 +0200 Subject: [PATCH 50/85] Change directory before trying to reset repository. Fixes #1489 --- automated install/basic-install.sh | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 5d893067..2f4459d4 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -220,6 +220,19 @@ getGitFiles() { return 0 } +resetRepo() { + local directory="${1}" + local curdir + + curdir="${PWD}" + cd "${directory}" &> /dev/null || return 1 + echo -n "::: Resetting repo in ${1}..." + git reset --hard &> /dev/null || return $? + echo " done!" + cd "${curdir}" &> /dev/null || return 1 + return 0 +} + find_IPv4_information() { local route # Find IP used to route to outside world @@ -1182,7 +1195,16 @@ update_dialogs() { clone_or_update_repos() { if [[ "${reconfigure}" == true ]]; then echo "::: --reconfigure passed to install script. Resetting changes to local repos" - git reset --hard + resetRepo ${PI_HOLE_LOCAL_REPO} || \ + { echo "!!! Unable to reset ${PI_HOLE_LOCAL_REPO}, unable to continue."; \ + exit 1; \ + } + if [[ ${INSTALL_WEB} == true ]]; then + resetRepo ${webInterfaceDir} || \ + { echo "!!! Unable to reset ${webInterfaceDir}, unable to continue."; \ + exit 1; \ + } + fi else # Get Git files for Core and Admin getGitFiles ${PI_HOLE_LOCAL_REPO} ${piholeGitUrl} || \ From 5004cf331abf54a80c12109ecc5f8f80538686f5 Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Mon, 22 May 2017 15:36:51 -0700 Subject: [PATCH 51/85] No need to `cd $PWD` as it doesn't affect flow of caller script. Signed-off-by: Dan Schaper --- automated install/basic-install.sh | 3 --- 1 file changed, 3 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 2f4459d4..ebf93f4a 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -222,14 +222,11 @@ getGitFiles() { resetRepo() { local directory="${1}" - local curdir - curdir="${PWD}" cd "${directory}" &> /dev/null || return 1 echo -n "::: Resetting repo in ${1}..." git reset --hard &> /dev/null || return $? echo " done!" - cd "${curdir}" &> /dev/null || return 1 return 0 } From 3035c9a366e2816397df3ab85e7abc8f2418cee3 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Tue, 23 May 2017 10:44:11 +0200 Subject: [PATCH 52/85] Refine output of password status in basic-install.sh:displayFinalMessage(). Fixes #1488 (#1490) --- automated install/basic-install.sh | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 5d893067..15fd93be 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -1129,10 +1129,18 @@ checkSelinux() { displayFinalMessage() { + if [[ ${#1} -gt 0 ]] ; then + pwstring="$1" + elif [[ $(grep 'WEBPASSWORD' -c /etc/pihole/setupVars.conf) -gt 0 ]]; then + pwstring="unchanged" + else + pwstring="NOT SET" + fi + if [[ ${INSTALL_WEB} == true ]]; then additional="View the web interface at http://pi.hole/admin or http://${IPV4_ADDRESS%/*}/admin -Your Admin Webpage login password is ${1:-"NOT SET"}" +Your Admin Webpage login password is ${pwstring}" fi # Final completion message to user From 4ad0cdf5d40d1b5bc1517837b62682366237a783 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 25 May 2017 01:03:13 +1000 Subject: [PATCH 53/85] Rewrite Chronometer to output more stats --- advanced/Scripts/chronometer.sh | 456 +++++++++++++++++++++++++++----- 1 file changed, 393 insertions(+), 63 deletions(-) diff --git a/advanced/Scripts/chronometer.sh b/advanced/Scripts/chronometer.sh index b5d54e5f..763091d8 100755 --- a/advanced/Scripts/chronometer.sh +++ b/advanced/Scripts/chronometer.sh @@ -8,98 +8,428 @@ # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. -# Functions -piLog="/var/log/pihole.log" -gravity="/etc/pihole/gravity.list" +# Retrieve stats from FTL engine +pihole-FTL() { + ftl_port=$(cat /var/run/pihole-FTL.port 2> /dev/null) + if [[ -n "$ftl_port" ]]; then + # Open connection to FTL + exec 3<>"/dev/tcp/localhost/$ftl_port" -. /etc/pihole/setupVars.conf + # Test if connection is open + if { "true" >&3; } 2> /dev/null; then + # Send command to FTL + echo -e ">$1" >&3 -function GetFTLData { - # Open connection to FTL - exec 3<>/dev/tcp/localhost/"$(cat /var/run/pihole-FTL.port)" + # Read input + read -r -t 1 LINE <&3 + until [[ ! $? ]] || [[ "$LINE" == *"EOM"* ]]; do + echo "$LINE" >&1 + read -r -t 1 LINE <&3 + done - # Test if connection is open - if { >&3; } 2> /dev/null; then - # Send command to FTL - echo -e ">$1" >&3 - - # Read input - read -r -t 1 LINE <&3 - until [ ! $? ] || [[ "$LINE" == *"EOM"* ]]; do - echo "$LINE" >&1 - read -r -t 1 LINE <&3 - done - - # Close connection - exec 3>&- - exec 3<&- + # Close connection + exec 3>&- + exec 3<&- + fi + else + echo -e "${COL_LIGHT_RED}FTL offline${COL_NC}" fi } -outputJSON() { - get_summary_data - echo "{\"domains_being_blocked\":${domains_being_blocked_raw},\"dns_queries_today\":${dns_queries_today_raw},\"ads_blocked_today\":${ads_blocked_today_raw},\"ads_percentage_today\":${ads_percentage_today_raw}}" +# Print spaces to align right-side content +printFunc() { + txt_len="${#2}" + + # Reduce string length when using colour code + [ "${2:0:1}" == "" ] && txt_len=$((txt_len-7)) + + if [[ "$3" == "last" ]]; then + # Prevent final line from printing trailing newline + scr_size=( $(stty size 2>/dev/null || echo 24 80) ) + scr_width="${scr_size[1]}" + + title_len="${#1}" + spc_num=$(( (scr_width - title_len) - txt_len )) + [[ "$spc_num" -lt 0 ]] && spc_num="0" + spc=$(printf "%${spc_num}s") + + printf "%s%s$spc" "$1" "$2" + else + # Determine number of spaces for padding + spc_num=$(( 20 - txt_len )) + [[ "$spc_num" -lt 0 ]] && spc_num="0" + spc=$(printf "%${spc_num}s") + + # Print string (Max 20 characters, prevents overflow) + printf "%s%s$spc" "$1" "${2:0:20}" + fi } -get_summary_data() { - local summary=$(GetFTLData "stats") - domains_being_blocked_raw=$(grep "domains_being_blocked" <<< "${summary}" | grep -Eo "[0-9]+$") - domains_being_blocked=$(printf "%'.f" ${domains_being_blocked_raw}) - dns_queries_today_raw=$(grep "dns_queries_today" <<< "$summary" | grep -Eo "[0-9]+$") - dns_queries_today=$(printf "%'.f" ${dns_queries_today_raw}) - ads_blocked_today_raw=$(grep "ads_blocked_today" <<< "$summary" | grep -Eo "[0-9]+$") - ads_blocked_today=$(printf "%'.f" ${ads_blocked_today_raw}) - ads_percentage_today_raw=$(grep "ads_percentage_today" <<< "$summary" | grep -Eo "[0-9.]+$") - LC_NUMERIC=C ads_percentage_today=$(printf "%'.f" ${ads_percentage_today_raw}) +# Perform on first Chrono run (not for JSON formatted string) +get_init_stats() { + LC_NUMERIC=C + calcFunc(){ awk "BEGIN {print $*}"; } + + # Convert bytes to human-readable format + hrBytes() { + awk '{ + num=$1; + if(num==0) { + print "0 B" + } else { + xxx=(num<0?-num:num) + sss=(num<0?-1:1) + split("B KB MB GB TB PB",type) + for(i=5;yyy < 1;i--) { + yyy=xxx / (2^(10*i)) + } + printf "%.0f " type[i+2], yyy*sss + } + }' <<< "$1"; + } + + # Convert seconds to human-readable format + hrSecs() { + day=$(( $1/60/60/24 )); hrs=$(( $1/3600%24 )); mins=$(( ($1%3600)/60 )); secs=$(( $1%60 )) + [[ "$day" -ge "2" ]] && plu="s" + [[ "$day" -ge "1" ]] && days="$day day${plu}, " || days="" + printf "%s%02d:%02d:%02d\n" "$days" "$hrs" "$mins" "$secs" + } + + # Set Colour Codes + coltable="/opt/pihole/COL_TABLE" + if [[ -f "${coltable}" ]]; then + source ${coltable} + else + COL_NC='' + COL_DARK_GRAY='' + COL_LIGHT_GREEN='' + COL_LIGHT_BLUE='' + COL_LIGHT_RED='' + COL_YELLOW='' + COL_LIGHT_RED='' + COL_URG_RED='' + fi + + # Get RPi model number, or OS distro info + if command -v vcgencmd &> /dev/null; then + sys_rev=$(awk '/Revision/ {print $3}' < /proc/cpuinfo) + case "$sys_rev" in + 000[2-6]) sys_model=" 1, Model B";; # 256MB + 000[7-9]) sys_model=" 1, Model A" ;; # 256MB + 000d|000e|000f) sys_model=" 1, Model B";; # 512MB + 0010|0013) sys_model=" 1, Model B+";; # 512MB + 0012|0015) sys_model=" 1, Model A+";; # 256MB + a0104[0-1]|a21041|a22042) sys_model=" 2, Model B";; # 1GB + 900021) sys_model=" 1, Model A+";; # 512MB + 900032) sys_model=" 1, Model B+";; # 512MB + 90009[2-3]|920093) sys_model=" Zero";; # 512MB + 9000c1) sys_model=" Zero W";; # 512MB + a02082|a[2-3]2082) sys_model=" 3, Model B";; # 1GB + *) sys_model="" ;; + esac + sys_type="Raspberry Pi$sys_model" + else + source "/etc/os-release" + CODENAME=$(sed 's/[()]//g' <<< "${VERSION/* /}") + sys_type="${NAME/ */} ${CODENAME^} $VERSION_ID" + fi + + # Get core count + sys_cores=$(grep -c "^processor" /proc/cpuinfo) + [[ "$sys_cores" -ne 1 ]] && sys_cores_plu="cores" || sys_cores_plu="core" + + # Test existence of clock speed file for ARM CPU + if [[ -f "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" ]]; then + scaling_freq_file="/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" + fi + + # Test existence of temperature file + if [[ -f "/sys/class/thermal/thermal_zone0/temp" ]]; then + temp_file="/sys/class/thermal/thermal_zone0/temp" + elif [[ -f "/sys/class/hwmon/hwmon0/temp1_input" ]]; then + temp_file="/sys/class/hwmon/hwmon0/temp1_input" + else + temp_file="" + fi + + # Test existence of setupVars config + if [[ -f "/etc/pihole/setupVars.conf" ]]; then + setupVars="/etc/pihole/setupVars.conf" + fi } -normalChrono() { +get_sys_stats() { + local ph_ver_raw + local cpu_raw + local ram_raw + local disk_raw + + # Update every 12 refreshes (Def: every 60s) + count=$((count+1)) + if [[ "$count" == "1" ]] || (( "$count" % 12 == 0 )); then + [[ -n "$setupVars" ]] && source "$setupVars" + + + ph_ver_raw=($(pihole -v -c 2> /dev/null | sed -n 's/^.* v/v/p')) + if [[ -n "${ph_ver_raw[0]}" ]]; then + ph_core_ver="${ph_ver_raw[0]}" + ph_lte_ver="${ph_ver_raw[1]}" + ph_ftl_ver="${ph_ver_raw[2]}" + else + ph_core_ver="${COL_LIGHT_RED}API unavailable${COL_NC}" + fi + + sys_name=$(hostname) + + [[ -n "$TEMPERATUREUNIT" ]] && temp_unit="$TEMPERATUREUNIT" || temp_unit="c" + + # Get storage stats for partition mounted on / + disk_raw=($(df -B1 / 2> /dev/null | awk 'END{ print $3,$2,$5 }')) + disk_used="${disk_raw[0]}" + disk_total="${disk_raw[1]}" + disk_perc="${disk_raw[2]}" + + net_gateway=$(route -n | awk '$4 == "UG" {print $2;exit}') + + # Get DHCP stats, if feature is enabled + if [[ "$DHCP_ACTIVE" == "true" ]]; then + ph_dhcp_eip="${DHCP_END##*.}" + ph_dhcp_max=$(( ${DHCP_END##*.} - ${DHCP_START##*.} + 1 )) + fi + + # Get alt DNS server, or print total count of alt DNS servers + if [[ -z "${PIHOLE_DNS_3}" ]]; then + ph_alts="${PIHOLE_DNS_2}" + else + dns_count="0" + [[ -n "${PIHOLE_DNS_2}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_3}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_4}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_5}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_6}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_7}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_8}" ]] && dns_count=$((dns_count+1)) + [[ -n "${PIHOLE_DNS_9}" ]] && dns_count="$dns_count+" + ph_alts="${dns_count} others" + fi + fi + + sys_uptime=$(hrSecs "$(cut -d. -f1 /proc/uptime)") + sys_loadavg=$(cut -d " " -f1,2,3 /proc/loadavg) + + # Get CPU usage, only counting processes over 1% CPU as active + cpu_raw=$(ps -eo pcpu,rss --no-headers | grep -E -v " 0") + cpu_tasks=$(wc -l <<< "$cpu_raw") + cpu_taskact=$(sed -r "/(^ 0.)/d" <<< "$cpu_raw" | wc -l) + cpu_perc=$(awk '{sum+=$1} END {printf "%.0f\n", sum/'"$sys_cores"'}' <<< "$cpu_raw") + + # Get CPU clock speed + if [[ -n "$scaling_freq_file" ]]; then + cpu_mhz=$(( $(< /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq) / 1000 )) + else + cpu_mhz=$(lscpu | awk -F "[ .]+" '/MHz/ {print $4;exit}') + fi + + # Determine correct string format for CPU clock speed + if [[ -n "$cpu_mhz" ]]; then + [[ "$cpu_mhz" -le "999" ]] && cpu_freq="$cpu_mhz MHz" || cpu_freq="$(calcFunc "$cpu_mhz"/1000) Ghz" + [[ -n "$cpu_freq" ]] && cpu_freq_str=" @ $cpu_freq" || cpu_freq_str="" + fi + + # Determine colour for temperature + if [[ -n "$temp_file" ]]; then + if [[ "$temp_unit" == "C" ]]; then + cpu_temp=$(printf "%'.0fc\n" "$(calcFunc "$(< $temp_file) / 1000")") + + case "${cpu_temp::-1}" in + -*|[0-9]|[1-3][0-9]) cpu_col="$COL_LIGHT_BLUE";; + 4[0-9]) cpu_col="";; + 5[0-9]) cpu_col="$COL_YELLOW";; + 6[0-9]) cpu_col="$COL_LIGHT_RED";; + *) cpu_col="$COL_URG_RED";; + esac + + # $COL_NC$COL_DARK_GRAY is needed for $COL_URG_RED + cpu_temp_str=", $cpu_col$cpu_temp$COL_NC$COL_DARK_GRAY" + + elif [[ "$temp_unit" == "F" ]]; then + cpu_temp=$(printf "%'.0ff\n" "$(calcFunc "($(< $temp_file) / 1000) * 9 / 5 + 32")") + + case "${cpu_temp::-1}" in + -*|[0-9]|[0-9][0-9]) cpu_col="$COL_LIGHT_BLUE";; + 1[0-1][0-9]) cpu_col="";; + 1[2-3][0-9]) cpu_col="$COL_YELLOW";; + 1[4-5][0-9]) cpu_col="$COL_LIGHT_RED";; + *) cpu_col="$COL_URG_RED";; + esac + + cpu_temp_str=", $cpu_col$cpu_temp$COL_NC$COL_DARK_GRAY" + + else + cpu_temp_str=$(printf ", %'.0fk\n" "$(calcFunc "($(< $temp_file) / 1000) + 273.15")") + fi + else + cpu_temp_str="" + fi + + ram_raw=($(awk '/MemTotal:/{total=$2} /MemFree:/{free=$2} /Buffers:/{buffers=$2} /^Cached:/{cached=$2} END {printf "%.0f %.0f %.0f", (total-free-buffers-cached)*100/total, (total-free-buffers-cached)*1024, total*1024}' /proc/meminfo)) + ram_perc="${ram_raw[0]}" + ram_used="${ram_raw[1]}" + ram_total="${ram_raw[2]}" + + if [[ "$(pihole status web 2> /dev/null)" == "1" ]]; then + ph_status="${COL_LIGHT_GREEN}Active" + else + ph_status="${COL_LIGHT_RED}Inactive" + fi + + if [[ "$DHCP_ACTIVE" == "true" ]]; then + ph_dhcp_num=$(wc -l 2> /dev/null < "/etc/pihole/dhcp.leases") + fi +} + +get_ftl_stats() { + local stats_raw + + stats_raw=($(pihole-FTL "stats")) + domains_being_blocked_raw="${stats_raw[1]}" + dns_queries_today_raw="${stats_raw[3]}" + ads_blocked_today_raw="${stats_raw[5]}" + ads_percentage_today_raw="${stats_raw[7]}" + + # Only retrieve these stats when not called from jsonFunc + if [[ -z "$1" ]]; then + local recent_blocked_raw + local top_ad_raw + local top_domain_raw + local top_client_raw + + domains_being_blocked=$(printf "%'.0f\n" "${domains_being_blocked_raw}") + dns_queries_today=$(printf "%'.0f\n" "${dns_queries_today_raw}") + ads_blocked_today=$(printf "%'.0f\n" "${ads_blocked_today_raw}") + ads_percentage_today=$(printf "%'.0f\n" "${ads_percentage_today_raw}") + + recent_blocked_raw=$(pihole-FTL recentBlocked) + top_ad_raw=($(pihole-FTL "top-ads (1)")) + top_domain_raw=($(pihole-FTL "top-domains (1)")) + top_client_raw=($(pihole-FTL "top-clients (1)")) + + # Limit strings to 40 characters to prevent overflow + recent_blocked="${recent_blocked_raw:0:40}" + top_ad="${top_ad_raw[2]:0:40}" + top_domain="${top_domain_raw[2]:0:40}" + [[ "${top_client_raw[3]}" ]] && top_client="${top_client_raw[3]:0:40}" || top_client="${top_client_raw[2]:0:40}" + fi +} + +chronoFunc() { + get_init_stats + for (( ; ; )); do - get_summary_data - domain=$(GetFTLData recentBlocked) + get_sys_stats + get_ftl_stats + + # Do not print LTE/FTL strings if API is unavailable + ph_core_str=" ${COL_DARK_GRAY}Pi-hole: $ph_core_ver${COL_NC}" + if [[ -n "$ph_lte_ver" ]]; then + ph_lte_str=" ${COL_DARK_GRAY}AdminLTE: $ph_lte_ver${COL_NC}" + ph_ftl_str=" ${COL_DARK_GRAY}FTL: $ph_ftl_ver${COL_NC}" + fi + clear - # Displays a colorful Pi-hole logo - echo " ___ _ _ _" - echo "| _ (_)___| |_ ___| |___" - echo "| _/ |___| ' \/ _ \ / -_)" - echo "|_| |_| |_||_\___/_\___|" - echo "" - echo " ${IPV4_ADDRESS}" - echo "" - uptime | cut -d' ' -f11- - #uptime -p # Doesn't work on all versions of uptime - uptime | awk -F'( |,|:)+' '{if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes."}' - echo "-------------------------------" - echo "Recently blocked:" - echo " $domain" + + echo -e "|¯¯¯(¯)__|¯|_ ___|¯|___$ph_core_str +| ¯_/¯|__| ' \/ _ \ / -_)$ph_lte_str +|_| |_| |_||_\___/_\___|$ph_ftl_str + ${COL_DARK_GRAY}——————————————————————————————————————————————————————————${COL_NC}" - echo "Blocking: ${domains_being_blocked}" - echo "Queries: ${dns_queries_today}" - echo "Pi-holed: ${ads_blocked_today} (${ads_percentage_today}%)" - - sleep 5 + printFunc " Hostname: " "$sys_name" + [ -n "$sys_type" ] && printf "%s(%s)%s\n" "$COL_DARK_GRAY" "$sys_type" "$COL_NC" || printf "\n" + + printf "%s\n" " Uptime: $sys_uptime" + + printFunc " Task Load: " "$sys_loadavg" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Active: $cpu_taskact of $cpu_tasks tasks" "$COL_NC" + + printFunc " CPU usage: " "$cpu_perc%" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "$sys_cores $sys_cores_plu$cpu_freq_str$cpu_temp_str" "$COL_NC" + + printFunc " RAM usage: " "$ram_perc%" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Used: $(hrBytes "$ram_used") of $(hrBytes "$ram_total")" "$COL_NC" + + printFunc " HDD usage: " "$disk_perc" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Used: $(hrBytes "$disk_used") of $(hrBytes "$disk_total")" "$COL_NC" + + printFunc " LAN addr: " "${IPV4_ADDRESS:0:-3}" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Gateway: $net_gateway" "$COL_NC" + + if [[ "$DHCP_ACTIVE" == "true" ]]; then + printFunc " DHCP: " "$DHCP_START to $ph_dhcp_eip" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Leased: $ph_dhcp_num of $ph_dhcp_max" "$COL_NC" + fi + + printFunc " Pi-hole: " "$ph_status" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Blocking: $domains_being_blocked sites" "$COL_NC" + + printFunc " Ads Today: " "$ads_percentage_today%" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "$ads_blocked_today of $dns_queries_today queries" "$COL_NC" + + printFunc " Fwd DNS: " "$PIHOLE_DNS_1" + printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Alt DNS: $ph_alts" "$COL_NC" + + echo -e " ${COL_DARK_GRAY}——————————————————————————————————————————————————————————${COL_NC}" + echo " Recently blocked: $recent_blocked" + echo " Top Advertiser: $top_ad" + echo " Top Domain: $top_domain" + printFunc " Top Client: " "$top_client" "last" + + if [[ "$1" == "exit" ]]; then + exit 0 + else + if [[ -n "$1" ]]; then + sleep "${1}" + else + sleep 5 + fi + fi + done } -displayHelp() { - echo "Usage: pihole -c [options] +jsonFunc() { + get_ftl_stats "json" + echo "{\"domains_being_blocked\":${domains_being_blocked_raw},\"dns_queries_today\":${dns_queries_today_raw},\"ads_blocked_today\":${ads_blocked_today_raw},\"ads_percentage_today\":${ads_percentage_today_raw}}" +} + +helpFunc() { + if [[ "$1" == "?" ]]; then + echo "Unknown option. Please view 'pihole -c --help' for more information" + else + echo "Usage: pihole -c [options] Example: 'pihole -c -j' Calculates stats and displays to an LCD Options: -j, --json Output stats as JSON formatted string + -r, --refresh Set update frequency (in seconds) + -e, --exit Output stats and exit witout refreshing -h, --help Display this help text" + fi + exit 0 } if [[ $# = 0 ]]; then - normalChrono + chronoFunc fi for var in "$@"; do case "$var" in - "-j" | "--json" ) outputJSON;; - "-h" | "--help" ) displayHelp;; - * ) exit 1;; + "-j" | "--json" ) jsonFunc;; + "-h" | "--help" ) helpFunc;; + "-r" | "--refresh" ) chronoFunc "$2";; + "-e" | "--exit" ) chronoFunc "exit";; + * ) helpFunc "?";; esac done From 10139241f5168e53015dd8e238f44289882c76e3 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Fri, 26 May 2017 17:57:27 +1000 Subject: [PATCH 54/85] Fix output IPv4 addr when removing CIDR notation (#1498) --- advanced/Scripts/chronometer.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/advanced/Scripts/chronometer.sh b/advanced/Scripts/chronometer.sh index 763091d8..d9b7d05b 100755 --- a/advanced/Scripts/chronometer.sh +++ b/advanced/Scripts/chronometer.sh @@ -361,7 +361,7 @@ chronoFunc() { printFunc " HDD usage: " "$disk_perc" printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Used: $(hrBytes "$disk_used") of $(hrBytes "$disk_total")" "$COL_NC" - printFunc " LAN addr: " "${IPV4_ADDRESS:0:-3}" + printFunc " LAN addr: " "${IPV4_ADDRESS/\/*/}" printf "%s(%s)%s\n" "$COL_DARK_GRAY" "Gateway: $net_gateway" "$COL_NC" if [[ "$DHCP_ACTIVE" == "true" ]]; then From d9135347935d9150443e405b4d0ef92f64c03f63 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 27 May 2017 17:51:41 +0200 Subject: [PATCH 55/85] Move wildcards file if blocking is disabled (#1495) * Move wildcards file if blocking is diabled * Delete newline --- pihole | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/pihole b/pihole index f89b67b2..1fb985e1 100755 --- a/pihole +++ b/pihole @@ -176,6 +176,9 @@ Time: elif [[ "${1}" == "0" ]]; then # Disable Pi-hole sed -i 's/^addn-hosts=\/etc\/pihole\/gravity.list/#addn-hosts=\/etc\/pihole\/gravity.list/' /etc/dnsmasq.d/01-pihole.conf + if [[ -e "$wildcardlist" ]]; then + mv "$wildcardlist" "/etc/pihole/wildcard.list" + fi echo "::: Blocking has been disabled!" if [[ $# > 1 ]]; then if [[ "${2}" == *"s"* ]]; then @@ -199,6 +202,9 @@ Time: # Enable Pi-hole echo "::: Blocking has been enabled!" sed -i 's/^#addn-hosts/addn-hosts/' /etc/dnsmasq.d/01-pihole.conf + if [[ -e "/etc/pihole/wildcard.list" ]]; then + mv "/etc/pihole/wildcard.list" "$wildcardlist" + fi fi restartDNS } @@ -305,7 +311,7 @@ tricorderFunc() { echo "Please do not call Tricorder directly." exit 1 fi - + if ! timeout 2 nc -z tricorder.pi-hole.net 9998 &> /dev/null; then echo "Unable to connect to Pi-hole's Tricorder server." exit 1 From 2b8a8b03a82c942c54cf1d9d7605cfe065e1f149 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 28 May 2017 06:42:44 +1000 Subject: [PATCH 56/85] Roll back merge #1417 (#1494) --- pihole | 81 +++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 32 deletions(-) diff --git a/pihole b/pihole index 1fb985e1..08e6b094 100755 --- a/pihole +++ b/pihole @@ -80,49 +80,66 @@ updateGravityFunc() { exit 0 } -scanList() { +scanList(){ domain="${1}" list="${2}" method="${3}" - - if [[ "${method}" == "-exact" ]]; then - grep -i -E -l "(^|\s|\/)${domain}($|\s|\/)" ${list} + if [[ ${method} == "-exact" ]] ; then + grep -i -E "(^|\s)${domain}($|\s)" "${list}" else - grep -i "${domain}" ${list} + grep -i "${domain}" "${list}" fi } +processWildcards() { + IFS="." read -r -a array <<< "${1}" + for (( i=${#array[@]}-1; i>=0; i-- )); do + ar="" + for (( j=${#array[@]}-1; j>${#array[@]}-i-2; j-- )); do + if [[ $j == $((${#array[@]}-1)) ]]; then + ar="${array[$j]}" + else + ar="${array[$j]}.${ar}" + fi + done + echo "${ar}" + done +} + queryFunc() { + domain="${2}" method="${3}" + lists=( /etc/pihole/list.* /etc/pihole/blacklist.txt) + for list in ${lists[@]}; do + if [ -e "${list}" ]; then + result=$(scanList ${domain} ${list} ${method}) + # Remove empty lines before couting number of results + count=$(sed '/^\s*$/d' <<< "$result" | wc -l) + echo "::: ${list} (${count} results)" + if [[ ${count} > 0 ]]; then + echo "${result}" + fi + echo "" + else + echo "::: ${list} does not exist" + echo "" + fi + done - # If domain contains non ASCII characters, convert domain to punycode if python exists - # Cr: https://serverfault.com/a/335079 - if [[ -z "${2}" ]]; then - echo "::: No domain specified" - exit 1 - elif [[ "${2}" = *[![:ascii:]]* ]]; then - [[ "$(which python)" ]] && domain=$(python -c 'import sys;print sys.argv[1].decode("utf-8").encode("idna")' "${2}") - else - domain="${2}" + # Scan for possible wildcard matches + if [ -e "${wildcardlist}" ]; then + local wildcards=($(processWildcards "${domain}")) + for domain in ${wildcards[@]}; do + result=$(scanList "\/${domain}\/" ${wildcardlist}) + # Remove empty lines before couting number of results + count=$(sed '/^\s*$/d' <<< "$result" | wc -l) + if [[ ${count} > 0 ]]; then + echo "::: Wildcard blocking ${domain} (${count} results)" + echo "${result}" + echo "" + fi + done fi - - # Scan Whitelist, Blacklist and Wildcards - lists="/etc/pihole/whitelist.txt /etc/pihole/blacklist.txt $wildcardlist" - result=$(scanList ${domain} "${lists}" ${method}) - if [[ -n "$result" ]]; then - echo "$result" - [[ ! -t 1 ]] && exit 0 - fi - - # Scan Domains lists - result=$(scanList ${domain} "/etc/pihole/*.domains" ${method}) - if [[ -n "$result" ]]; then - sort -t . -k 2 -g <<< "$result" - else - [ -n "$method" ] && exact="exact " - echo "::: No ${exact}results found for ${domain}" - fi - exit 0 } From 570c54002f3dfb212dff57a3708e83b1b27a4252 Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Tue, 30 May 2017 23:51:22 -0700 Subject: [PATCH 57/85] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 3014625b..066b3f8f 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -9,7 +9,7 @@ _{replace this text with a number from 1 to 10, with 1 being not familiar, and 10 being very familiar}_ --- -**[FEATURE REQUEST | QUESTION | OTHER]:** +**[BUG REPORT | QUESTION | OTHER]:** Please [submit your feature request here](https://discourse.pi-hole.net/c/feature-requests), so it is votable by the community. It's also easier for us to track. From 3a58e9d33abf843e42c44d1bfda69339b468450b Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Wed, 31 May 2017 00:02:57 -0700 Subject: [PATCH 58/85] Remove Question option --- .github/ISSUE_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 066b3f8f..23e67795 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -9,7 +9,7 @@ _{replace this text with a number from 1 to 10, with 1 being not familiar, and 10 being very familiar}_ --- -**[BUG REPORT | QUESTION | OTHER]:** +**[BUG REPORT | OTHER]:** Please [submit your feature request here](https://discourse.pi-hole.net/c/feature-requests), so it is votable by the community. It's also easier for us to track. From 01e091fd170229c98d33adf96a8c207717cc16ea Mon Sep 17 00:00:00 2001 From: DL6ER Date: Fri, 2 Jun 2017 23:01:48 +0200 Subject: [PATCH 59/85] Prefer ULA over GUA addresses [IPv6] (#1508) * On installs with GUA and ULA's we should prefer ULA's as it's been demonstrated that GUA's can and often are rotated by ISPs. Fixes #1473 * Add test for link-local address detection * Add ULA-only and GUA-only tests * Add test_IPv6_GUA_ULA_test and test_IPv6_ULA_GUA_test * Add "" * Add mock_command_2 command that can mock a command with more than one argument (as "ip -6 address") and result multiple lines of results * Make mock_command_2 more similar to the original mock_command * Correct comments * Fixed remaining comments * Fixed one last comment... * Fixed a comment... --- automated install/basic-install.sh | 34 +++++++++++-- test/test_automated_install.py | 76 ++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 42e06bdf..b8b44550 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -327,16 +327,44 @@ chooseInterface() { fi } +# See https://github.com/pi-hole/pi-hole/issues/1473#issuecomment-301745953 +testIPv6() { + first="$(cut -f1 -d":" <<< "$1")" + value1=$(((0x$first)/256)) + value2=$(((0x$first)%256)) + ((($value1&254)==252)) && echo "ULA" || true + ((($value1&112)==32)) && echo "GUA" || true + ((($value1==254) && (($value2&192)==128))) && echo "Link-local" || true +} + useIPv6dialog() { - # Show the IPv6 address used for blocking - IPV6_ADDRESS=$(ip -6 route get 2001:4860:4860::8888 | grep -v "unreachable" | awk -F " " '{ for(i=1;i<=NF;i++) if ($i == "src") print $(i+1) }') + # Determine the IPv6 address used for blocking + IPV6_ADDRESSES=($(ip -6 address | grep 'scope global' | awk '{print $2}')) + + # Determine type of found IPv6 addresses + for i in "${IPV6_ADDRESSES[@]}"; do + result=$(testIPv6 "$i") + [[ "${result}" == "ULA" ]] && ULA_ADDRESS="$i" + [[ "${result}" == "GUA" ]] && GUA_ADDRESS="$i" + done + + # Determine which address to be used: Prefer ULA over GUA or don't use any if none found + if [[ ! -z "${ULA_ADDRESS}" ]]; then + IPV6_ADDRESS="${ULA_ADDRESS}" + echo "::: Found IPv6 ULA address, using it for blocking IPv6 ads" + elif [[ ! -z "${GUA_ADDRESS}" ]]; then + echo "::: Found IPv6 GUA address, using it for blocking IPv6 ads" + IPV6_ADDRESS="${GUA_ADDRESS}" + else + echo "::: Found neither IPv6 ULA nor GUA address, blocking IPv6 ads will not be enabled" + IPV6_ADDRESS="" + fi if [[ ! -z "${IPV6_ADDRESS}" ]]; then whiptail --msgbox --backtitle "IPv6..." --title "IPv6 Supported" "$IPV6_ADDRESS will be used to block ads." ${r} ${c} fi } - use4andor6() { local useIPv4 local useIPv6 diff --git a/test/test_automated_install.py b/test/test_automated_install.py index 8e36fc96..60772625 100644 --- a/test/test_automated_install.py +++ b/test/test_automated_install.py @@ -402,6 +402,61 @@ def test_FTL_binary_installed_and_responsive_no_errors(Pihole): # assert '644 /run/pihole-FTL.pid' in support_files.stdout # assert '644 /var/log/pihole-FTL.log' in support_files.stdout +def test_IPv6_only_link_local(Pihole): + ''' confirms IPv6 blocking is disabled for Link-local address ''' + # mock ip -6 address to return Link-local address + mock_command_2('ip', {'-6 address':('inet6 fe80::d210:52fa:fe00:7ad7/64 scope link', '0')}, Pihole) + detectPlatform = Pihole.run(''' + source /opt/pihole/basic-install.sh + useIPv6dialog + ''') + expected_stdout = 'Found neither IPv6 ULA nor GUA address, blocking IPv6 ads will not be enabled' + assert expected_stdout in detectPlatform.stdout + +def test_IPv6_only_ULA(Pihole): + ''' confirms IPv6 blocking is enabled for ULA addresses ''' + # mock ip -6 address to return ULA address + mock_command_2('ip', {'-6 address':('inet6 fda2:2001:5555:0:d210:52fa:fe00:7ad7/64 scope global', '0')}, Pihole) + detectPlatform = Pihole.run(''' + source /opt/pihole/basic-install.sh + useIPv6dialog + ''') + expected_stdout = 'Found IPv6 ULA address, using it for blocking IPv6 ads' + assert expected_stdout in detectPlatform.stdout + +def test_IPv6_only_GUA(Pihole): + ''' confirms IPv6 blocking is enabled for GUA addresses ''' + # mock ip -6 address to return GUA address + mock_command_2('ip', {'-6 address':('inet6 2003:12:1e43:301:d210:52fa:fe00:7ad7/64 scope global', '0')}, Pihole) + detectPlatform = Pihole.run(''' + source /opt/pihole/basic-install.sh + useIPv6dialog + ''') + expected_stdout = 'Found IPv6 GUA address, using it for blocking IPv6 ads' + assert expected_stdout in detectPlatform.stdout + +def test_IPv6_GUA_ULA_test(Pihole): + ''' confirms IPv6 blocking is enabled for GUA and ULA addresses ''' + # mock ip -6 address to return GUA and ULA addresses + mock_command_2('ip', {'-6 address':('inet6 2003:12:1e43:301:d210:52fa:fe00:7ad7/64 scope global\ninet6 fda2:2001:5555:0:d210:52fa:fe00:7ad7/64 scope global', '0')}, Pihole) + detectPlatform = Pihole.run(''' + source /opt/pihole/basic-install.sh + useIPv6dialog + ''') + expected_stdout = 'Found IPv6 ULA address, using it for blocking IPv6 ads' + assert expected_stdout in detectPlatform.stdout + +def test_IPv6_ULA_GUA_test(Pihole): + ''' confirms IPv6 blocking is enabled for GUA and ULA addresses ''' + # mock ip -6 address to return ULA and GUA addresses + mock_command_2('ip', {'-6 address':('inet6 fda2:2001:5555:0:d210:52fa:fe00:7ad7/64 scope global\ninet6 2003:12:1e43:301:d210:52fa:fe00:7ad7/64 scope global', '0')}, Pihole) + detectPlatform = Pihole.run(''' + source /opt/pihole/basic-install.sh + useIPv6dialog + ''') + expected_stdout = 'Found IPv6 ULA address, using it for blocking IPv6 ads' + assert expected_stdout in detectPlatform.stdout + # Helper functions def mock_command(script, args, container): ''' Allows for setup of commands we don't really want to have to run for real in unit tests ''' @@ -424,6 +479,27 @@ def mock_command(script, args, container): chmod +x {script} rm -f /var/log/{scriptlog}'''.format(script=full_script_path, content=mock_script, scriptlog=script)) +def mock_command_2(script, args, container): + ''' Allows for setup of commands we don't really want to have to run for real in unit tests ''' + full_script_path = '/usr/local/bin/{}'.format(script) + mock_script = dedent('''\ + #!/bin/bash -e + echo "\$0 \$@" >> /var/log/{script} + case "\$1 \$2" in'''.format(script=script)) + for k, v in args.iteritems(): + case = dedent(''' + \"{arg}\") + echo \"{res}\" + exit {retcode} + ;;'''.format(arg=k, res=v[0], retcode=v[1])) + mock_script += case + mock_script += dedent(''' + esac''') + container.run(''' + cat < {script}\n{content}\nEOF + chmod +x {script} + rm -f /var/log/{scriptlog}'''.format(script=full_script_path, content=mock_script, scriptlog=script)) + def run_script(Pihole, script): result = Pihole.run(script) assert result.rc == 0 From 8ef64dbe7491c9028a45b14d415bcf86d6743bbf Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 3 Jun 2017 14:51:35 +0200 Subject: [PATCH 60/85] Add weekly logrotation of FTL's log (#1509) --- advanced/logrotate | 11 +++++++++++ automated install/basic-install.sh | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/advanced/logrotate b/advanced/logrotate index 570e7548..ffed910b 100644 --- a/advanced/logrotate +++ b/advanced/logrotate @@ -8,3 +8,14 @@ notifempty nomail } + +/var/log/pihole-FTL.log { + # su # + weekly + copytruncate + rotate 3 + compress + delaycompress + notifempty + nomail +} diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index b8b44550..e8b28f62 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -1080,7 +1080,7 @@ installLogrotate() { # the local properties of the /var/log directory logusergroup="$(stat -c '%U %G' /var/log)" if [[ ! -z $logusergroup ]]; then - sed -i "s/# su #/su ${logusergroup}/" /etc/pihole/logrotate + sed -i "s/# su #/su ${logusergroup}/g;" /etc/pihole/logrotate fi echo " done!" } From 288f93c5dd3c3646991e454c461927ac057d8eba Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 3 Jun 2017 15:06:00 +0200 Subject: [PATCH 61/85] Update LICENSE of the project to EUPL v1.2 --- LICENSE | 119 +++++++++++++++++++++++--------------------------------- 1 file changed, 49 insertions(+), 70 deletions(-) diff --git a/LICENSE b/LICENSE index 9fddaad1..9ce6e5b0 100644 --- a/LICENSE +++ b/LICENSE @@ -12,81 +12,63 @@ This license applies to the whole project EXCEPT: The licenses that existed prior to this change have remained intact. ------------------------------------------------------------- +EUROPEAN UNION PUBLIC LICENCE v. 1.2 -European Union Public Licence -V. 1.1 +EUPL © the European Union 2007, 2016 -EUPL (C) the European Community 2007 - -This European Union Public Licence (the "EUPL") applies to the Work or Software (as defined below) which is provided under the terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such use is covered by a right of the copyright holder of the Work). - -The Original Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following notice immediately following the copyright notice for the Original Work: - -Licensed under the EUPL V.1.1 - -or has expressed by any other mean his willingness to license under the EUPL. +This European Union Public Licence (the EUPL) applies to the Work (as defined below) which is provided under the terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such use is covered by a right of the copyright holder of the Work). +The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following notice immediately following the copyright notice for the Work: +Licensed under the EUPL +or has expressed by any other means his willingness to license under the EUPL. 1. Definitions In this Licence, the following terms have the following meaning: - The Licence: this Licence. - -- The Original Work or the Software: the software distributed and/or communicated by the Licensor under this Licence, available as Source Code and also as Executable Code as the case may be. - +- The Original Work: the work or software distributed or communicated by the Licensor under this Licence, available as Source Code and also as Executable Code as the case may be. - Derivative Works: the works or software that could be created by the Licensee, based upon the Original Work or modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in the country mentioned in Article 15. - -- The Work: the Original Work and/or its Derivative Works. - +- The Work: the Original Work or its Derivative Works. - The Source Code: the human-readable form of the Work which is the most convenient for people to study and modify. - - The Executable Code: any code which has generally been compiled and which is meant to be interpreted by a computer as a program. - -- The Licensor: the natural or legal person that distributes and/or communicates the Work under the Licence. - +- The Licensor: the natural or legal person that distributes or communicates the Work under the Licence. - Contributor(s): any natural or legal person who modifies the Work under the Licence, or otherwise contributes to the creation of a Derivative Work. - -- The Licensee or "You": any natural or legal person who makes any usage of the Software under the terms of the Licence. - -- Distribution and/or Communication: any act of selling, giving, lending, renting, distributing, communicating, transmitting, or otherwise making available, on-line or off-line, copies of the Work or providing access to its essential functionalities at the disposal of any other natural or legal person. +- The Licensee or You: any natural or legal person who makes any usage of the Work under the terms of the Licence. +- Distribution or Communication: any act of selling, giving, lending, renting, distributing, communicating, transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential functionalities at the disposal of any other natural or legal person. 2. Scope of the rights granted by the Licence -The Licensor hereby grants You a world-wide, royalty-free, non-exclusive, sub-licensable licence to do the following, for the duration of copyright vested in the Original Work: - +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for the duration of copyright vested in the Original Work: - use the Work in any circumstance and for all usage, - reproduce the Work, -- modify the Original Work, and make Derivative Works based upon the Work, +- modify the Work, and make Derivative Works based upon the Work, - communicate to the public, including the right to make available or display the Work or copies thereof to the public and perform publicly, as the case may be, the Work, - distribute the Work or copies thereof, - lend and rent the Work or copies thereof, -- sub-license rights in the Work or copies thereof. - +- sublicense rights in the Work or copies thereof. Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the applicable law permits so. - In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed by law in order to make effective the licence of the economic rights here above listed. - -The Licensor grants to the Licensee royalty-free, non exclusive usage rights to any patents held by the Licensor, to the extent necessary to make use of the rights granted on the Work under this Licence. +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the extent necessary to make use of the rights granted on the Work under this Licence. 3. Communication of the Source Code -The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to distribute and/or communicate the Work. +The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to distribute or communicate the Work. 4. Limitations on copyright -Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the exclusive rights of the rights owners in the Original Work or Software, of the exhaustion of those rights or of other applicable limitations thereto. +Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations thereto. 5. Obligations of the Licensee The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those obligations are the following: -Attribution right: the Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the Licence with every copy of the Work he/she distributes and/or communicates. The Licensee must cause any Derivative Work to carry prominent notices stating that the Work has been modified and the date of modification. +Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work to carry prominent notices stating that the Work has been modified and the date of modification. -Copyleft clause: If the Licensee distributes and/or communicates copies of the Original Works or Derivative Works based upon the Original Work, this Distribution and/or Communication will be done under the terms of this Licence or of a later version of this Licence unless the Original Work is expressly distributed only under this version of the Licence. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the Work or Derivative Work that alter or restrict the terms of the Licence. +Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless the Original Work is expressly distributed only under this version of the Licence - for example by communicating EUPL v. 1.2 only. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the Work or Derivative Work that alter or restrict the terms of the Licence. -Compatibility clause: If the Licensee Distributes and/or Communicates Derivative Works or copies thereof based upon both the Original Work and another work licensed under a Compatible Licence, this Distribution and/or Communication can be done under the terms of this Compatible Licence. For the sake of this clause, "Compatible Licence" refers to the licences listed in the appendix attached to this Licence. Should the Licensee’s obligations under the Compatible Licence conflict with his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. +Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done under the terms of this Compatible Licence. For the sake of this clause, Compatible Licence refers to the licences listed in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. -Provision of Source Code: When distributing and/or communicating copies of the Work, the Licensee will provide a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available for as long as the Licensee continues to distribute and/or communicate the Work. +Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available for as long as the Licensee continues to distribute or communicate the Work. Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the copyright notice. @@ -100,10 +82,8 @@ Each time You accept the Licence, the original Licensor and subsequent Contribut 7. Disclaimer of Warranty -The Work is a work in progress, which is continuously improved by numerous contributors. It is not a finished work and may therefore contain defects or "bugs" inherent to this type of software development. - -For the above reason, the Work is provided under the Licence on an "as is" basis and without warranties of any kind concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this Licence. - +The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work and may therefore contain defects or bugs inherent to this type of development. +For the above reason, the Work is provided under the Licence on an as is basis and without warranties of any kind concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this Licence. This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work. 8. Disclaimer of Liability @@ -112,56 +92,55 @@ Except in the cases of wilful misconduct or damages directly caused to natural p 9. Additional agreements -While distributing the Original Work or Derivative Works, You may choose to conclude an additional agreement to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or services consistent with this Licence. However, in accepting such obligations, You may act only on your own behalf and on your sole responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by the fact You have accepted any such warranty or additional liability. +While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by the fact You have accepted any warranty or additional liability. 10. Acceptance of the Licence -The provisions of this Licence can be accepted by clicking on an icon "I agree" placed under the bottom of a window displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms and conditions. - -Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution and/or Communication by You of the Work or copies thereof. +The provisions of this Licence can be accepted by clicking on an icon I agree placed under the bottom of a window displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms and conditions. +Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution or Communication by You of the Work or copies thereof. 11. Information to the public -In case of any Distribution and/or Communication of the Work by means of electronic communication by You (for example, by offering to download the Work from a remote location) the distribution channel or media (for example, a website) must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence and the way it may be accessible, concluded, stored and reproduced by the Licensee. +In case of any Distribution or Communication of the Work by means of electronic communication by You (for example, by offering to download the Work from a remote location) the distribution channel or media (for example, a website) must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence and the way it may be accessible, concluded, stored and reproduced by the Licensee. 12. Termination of the Licence The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms of the Licence. - Such a termination will not terminate the licences of any person who has received the Work from the Licensee under the Licence, provided such persons remain in full compliance with the Licence. 13. Miscellaneous -Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the Work licensed hereunder. - -If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or enforceability of the Licence as a whole. Such provision will be construed and/or reformed so as necessary to make it valid and enforceable. - -The European Commission may publish other linguistic versions and/or new versions of this Licence, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. New versions of the Licence will be published with a unique version number. - +Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the Work. +If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid and enforceable. +The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. New versions of the Licence will be published with a unique version number. All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take advantage of the linguistic version of their choice. 14. Jurisdiction -Any litigation resulting from the interpretation of this License, arising between the European Commission, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice of the European Communities, as laid down in article 238 of the Treaty establishing the European Community. - -Any litigation arising between Parties, other than the European Commission, and resulting from the interpretation of this License, will be subject to the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. +Without prejudice to specific agreement between parties, +- any litigation resulting from the interpretation of this License, arising between the European Union institutions, bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union, +- any litigation arising between other parties and resulting from the interpretation of this License, will be subject to the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. 15. Applicable Law -This Licence shall be governed by the law of the European Union country where the Licensor resides or has his registered office. - -This licence shall be governed by the Belgian law if: - -- a litigation arises between the European Commission, as a Licensor, and any Licensee; -- the Licensor, other than the European Commission, has no residence or registered office inside a European Union country. - +Without prejudice to specific agreement between parties, +- this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat, resides or has his registered office, +- this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside a European Union Member State. === + Appendix -"Compatible Licences" according to article 5 EUPL are: -- GNU General Public License (GNU GPL) v. 2 +Compatible Licences according to Article 5 EUPL are: +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 - Open Software License (OSL) v. 2.1, v. 3.0 -- Common Public License v. 1.0 -- Eclipse Public License v. 1.0 -- Cecill v. 2.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence - Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+) +- The European Commission may update this Appendix to later versions of the above licences without producing a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the covered Source Code from exclusive appropriation. +- All other changes or additions to this Appendix require the production of a new EUPL version. From 2516a1e298068aacc3d98d198caee10277c9460c Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 3 Jun 2017 17:23:47 +0200 Subject: [PATCH 62/85] Make clear that NO is the default if the user just hits return (#1514) --- advanced/Scripts/piholeCheckout.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/advanced/Scripts/piholeCheckout.sh b/advanced/Scripts/piholeCheckout.sh index 286edb2e..e2c0ab11 100644 --- a/advanced/Scripts/piholeCheckout.sh +++ b/advanced/Scripts/piholeCheckout.sh @@ -87,7 +87,7 @@ warning1() { 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 -e " ${red}This feature is NOT supported unless a Pi-hole developer explicitly asks!${def}" - 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 [yY][eE][sS]|[yY]) echo "::: Continuing with branch change." From 6823a6264455a28242a30b46d1a5fc759d5f12b3 Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Sun, 4 Jun 2017 03:13:40 +1000 Subject: [PATCH 63/85] Add tricorderFunc back as usable function (#1515) As per #1464 --- pihole | 1 + 1 file changed, 1 insertion(+) diff --git a/pihole b/pihole index 08e6b094..f2bc7000 100755 --- a/pihole +++ b/pihole @@ -423,5 +423,6 @@ case "${1}" in "-a" | "admin" ) webpageFunc "$@";; "-t" | "tail" ) tailFunc;; "checkout" ) piholeCheckoutFunc "$@";; + "tricorder" ) tricorderFunc;; * ) helpFunc;; esac From f1146a344356a6e9b74dc02f70d92f4f9fccf1a0 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sun, 4 Jun 2017 12:40:57 +0200 Subject: [PATCH 64/85] Don't update FTL when there is a core update (as this will update FTL a second time). Fixes #1516 --- advanced/Scripts/update.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/advanced/Scripts/update.sh b/advanced/Scripts/update.sh index 4fceb931..24b30de4 100755 --- a/advanced/Scripts/update.sh +++ b/advanced/Scripts/update.sh @@ -117,7 +117,10 @@ main() { echo "::: FTL: up to date" fi - if ${FTL_update}; then + # Logic: Don't update FTL when there is a core update available + # since the core update will run the installer which will itself + # re-install (i.e. update) FTL + if ${FTL_update} && ! ${core_update}; then echo ":::" echo "::: FTL out of date" FTLdetect From cf6a1ac9adb4e26570cc5da7c8be628080f37e0f Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sun, 4 Jun 2017 13:23:56 +0200 Subject: [PATCH 65/85] Add FTL tests to the test suite (#1510) * Add first version of FTL tests * Wait one second to allow FTL to start up and analyze our mock log * Add test_FTL_telnet_statistics * Added test_FTL_telnet_top_clients * Add test_FTL_telnet_top_domains --- test/FTL-test.sh | 76 ++++++++++++++++++++++++++++++++++ test/test_automated_install.py | 64 ++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100755 test/FTL-test.sh diff --git a/test/FTL-test.sh b/test/FTL-test.sh new file mode 100755 index 00000000..7e139c8a --- /dev/null +++ b/test/FTL-test.sh @@ -0,0 +1,76 @@ +#!/bin/bash +FTL_communicate() { + # Open connection to FTL + exec 3<>"/dev/tcp/localhost/4711" + + # Test if connection is open + if { "true" >&3; } 2> /dev/null; then + # Send command to FTL + echo -e ">$1" >&3 + + # Read input + read -r -t 1 LINE <&3 + until [[ ! $? ]] || [[ "$LINE" == *"EOM"* ]]; do + echo "$LINE" >&1 + read -r -t 1 LINE <&3 + done + + # Close connection + exec 3>&- + exec 3<&- + fi +} + +FTL_get_version() { + FTL_communicate "version" +} + +FTL_get_stats() { + FTL_communicate "stats" +} + +FTL_get_top_clients() { + FTL_communicate "top-clients" +} + +FTL_get_top_domains() { + FTL_communicate "top-domains" +} + +FTL_prepare_files() { + ts=$(dnsmasq_pre) +cat <> /var/log/pihole.log +${ts} query[AAAA] raspberrypi from 127.0.0.1 +${ts} /etc/pihole/local.list raspberrypi is fda2:2001:5647:0:ba27:ebff:fe37:4205 +${ts} query[A] checkip.dyndns.org from 127.0.0.1 +${ts} forwarded checkip.dyndns.org to 2001:1608:10:25::9249:d69b +${ts} forwarded checkip.dyndns.org to 2001:1608:10:25::1c04:b12f +${ts} forwarded checkip.dyndns.org to 2620:0:ccd::2 +${ts} forwarded checkip.dyndns.org to 2620:0:ccc::2 +${ts} reply checkip.dyndns.org is +${ts} reply checkip.dyndns.com is 216.146.38.70 +${ts} reply checkip.dyndns.com is 216.146.43.71 +${ts} reply checkip.dyndns.com is 91.198.22.70 +${ts} reply checkip.dyndns.com is 216.146.43.70 +${ts} query[A] pi.hole from 10.8.0.2 +${ts} /etc/pihole/local.list pi.hole is 192.168.2.10 +${ts} query[A] play.google.com from 192.168.2.208 +${ts} forwarded play.google.com to 2001:1608:10:25::9249:d69b +${ts} forwarded play.google.com to 2001:1608:10:25::1c04:b12f +${ts} forwarded play.google.com to 2620:0:ccd::2 +${ts} forwarded play.google.com to 2620:0:ccc::2 +${ts} reply play.google.com is +${ts} reply play.l.google.com is 216.58.208.110 +${ts} reply play.l.google.com is 216.58.208.110 +${ts} reply play.l.google.com is 216.58.208.110 +${ts} reply play.google.com is +${ts} query[AAAA] play.google.com from 192.168.2.208 +${ts} forwarded play.google.com to 2620:0:ccd::2 +${ts} reply play.l.google.com is 2a00:1450:4017:802::200e +EOT +} + +dnsmasq_pre() { + echo -n $(date +"%b %e %H:%M:%S") + echo -n "dnsmasq[123]:" +} diff --git a/test/test_automated_install.py b/test/test_automated_install.py index 60772625..60a0f123 100644 --- a/test/test_automated_install.py +++ b/test/test_automated_install.py @@ -402,6 +402,70 @@ def test_FTL_binary_installed_and_responsive_no_errors(Pihole): # assert '644 /run/pihole-FTL.pid' in support_files.stdout # assert '644 /var/log/pihole-FTL.log' in support_files.stdout +def test_FTL_telnet_version(Pihole): + ''' confirms FTL binary is copied and functional in installed location and through telnet ''' + FTLtest = Pihole.run(''' + source /opt/pihole/basic-install.sh + source /etc/.pihole/test/FTL-test.sh + FTL_prepare_files + FTLdetect + pihole-FTL + sleep 1 + FTL_get_version + ''') + assert 'version' in FTLtest.stdout + assert 'tag' in FTLtest.stdout + assert 'branch' in FTLtest.stdout + assert 'date' in FTLtest.stdout + +def test_FTL_telnet_statistics(Pihole): + ''' confirms FTL binary is copied and functional in installed location and through telnet ''' + FTLtest = Pihole.run(''' + source /opt/pihole/basic-install.sh + source /etc/.pihole/test/FTL-test.sh + FTL_prepare_files + FTLdetect + pihole-FTL + sleep 1 + FTL_get_stats + ''') + assert 'domains_being_blocked' in FTLtest.stdout + assert 'dns_queries_today 5' in FTLtest.stdout + assert 'unique_domains 4' in FTLtest.stdout + assert 'queries_forwarded 3' in FTLtest.stdout + assert 'queries_cached 2' in FTLtest.stdout + +def test_FTL_telnet_top_clients(Pihole): + ''' confirms FTL binary is copied and functional in installed location and through telnet ''' + FTLtest = Pihole.run(''' + source /opt/pihole/basic-install.sh + source /etc/.pihole/test/FTL-test.sh + FTL_prepare_files + FTLdetect + pihole-FTL + sleep 1 + FTL_get_top_clients + ''') + assert '0 2 192.168.2.208' in FTLtest.stdout + assert '1 2 127.0.0.1' in FTLtest.stdout + assert '2 1 10.8.0.2' in FTLtest.stdout + +def test_FTL_telnet_top_domains(Pihole): + ''' confirms FTL binary is copied and functional in installed location and through telnet ''' + FTLtest = Pihole.run(''' + source /opt/pihole/basic-install.sh + source /etc/.pihole/test/FTL-test.sh + FTL_prepare_files + FTLdetect + pihole-FTL + sleep 1 + FTL_get_top_domains + ''') + assert '0 2 play.google.com' in FTLtest.stdout + assert '1 1 pi.hole' in FTLtest.stdout + assert '2 1 checkip.dyndns.org' in FTLtest.stdout + assert '3 1 raspberrypi' in FTLtest.stdout + def test_IPv6_only_link_local(Pihole): ''' confirms IPv6 blocking is disabled for Link-local address ''' # mock ip -6 address to return Link-local address From 939055f19c2e2389b9a9db8db263f9cd26838a17 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Mon, 5 Jun 2017 13:51:13 +0200 Subject: [PATCH 66/85] Revert "Add FTL tests to the test suite (#1510)" (#1519) This reverts commit cf6a1ac9adb4e26570cc5da7c8be628080f37e0f. --- test/FTL-test.sh | 76 ---------------------------------- test/test_automated_install.py | 64 ---------------------------- 2 files changed, 140 deletions(-) delete mode 100755 test/FTL-test.sh diff --git a/test/FTL-test.sh b/test/FTL-test.sh deleted file mode 100755 index 7e139c8a..00000000 --- a/test/FTL-test.sh +++ /dev/null @@ -1,76 +0,0 @@ -#!/bin/bash -FTL_communicate() { - # Open connection to FTL - exec 3<>"/dev/tcp/localhost/4711" - - # Test if connection is open - if { "true" >&3; } 2> /dev/null; then - # Send command to FTL - echo -e ">$1" >&3 - - # Read input - read -r -t 1 LINE <&3 - until [[ ! $? ]] || [[ "$LINE" == *"EOM"* ]]; do - echo "$LINE" >&1 - read -r -t 1 LINE <&3 - done - - # Close connection - exec 3>&- - exec 3<&- - fi -} - -FTL_get_version() { - FTL_communicate "version" -} - -FTL_get_stats() { - FTL_communicate "stats" -} - -FTL_get_top_clients() { - FTL_communicate "top-clients" -} - -FTL_get_top_domains() { - FTL_communicate "top-domains" -} - -FTL_prepare_files() { - ts=$(dnsmasq_pre) -cat <> /var/log/pihole.log -${ts} query[AAAA] raspberrypi from 127.0.0.1 -${ts} /etc/pihole/local.list raspberrypi is fda2:2001:5647:0:ba27:ebff:fe37:4205 -${ts} query[A] checkip.dyndns.org from 127.0.0.1 -${ts} forwarded checkip.dyndns.org to 2001:1608:10:25::9249:d69b -${ts} forwarded checkip.dyndns.org to 2001:1608:10:25::1c04:b12f -${ts} forwarded checkip.dyndns.org to 2620:0:ccd::2 -${ts} forwarded checkip.dyndns.org to 2620:0:ccc::2 -${ts} reply checkip.dyndns.org is -${ts} reply checkip.dyndns.com is 216.146.38.70 -${ts} reply checkip.dyndns.com is 216.146.43.71 -${ts} reply checkip.dyndns.com is 91.198.22.70 -${ts} reply checkip.dyndns.com is 216.146.43.70 -${ts} query[A] pi.hole from 10.8.0.2 -${ts} /etc/pihole/local.list pi.hole is 192.168.2.10 -${ts} query[A] play.google.com from 192.168.2.208 -${ts} forwarded play.google.com to 2001:1608:10:25::9249:d69b -${ts} forwarded play.google.com to 2001:1608:10:25::1c04:b12f -${ts} forwarded play.google.com to 2620:0:ccd::2 -${ts} forwarded play.google.com to 2620:0:ccc::2 -${ts} reply play.google.com is -${ts} reply play.l.google.com is 216.58.208.110 -${ts} reply play.l.google.com is 216.58.208.110 -${ts} reply play.l.google.com is 216.58.208.110 -${ts} reply play.google.com is -${ts} query[AAAA] play.google.com from 192.168.2.208 -${ts} forwarded play.google.com to 2620:0:ccd::2 -${ts} reply play.l.google.com is 2a00:1450:4017:802::200e -EOT -} - -dnsmasq_pre() { - echo -n $(date +"%b %e %H:%M:%S") - echo -n "dnsmasq[123]:" -} diff --git a/test/test_automated_install.py b/test/test_automated_install.py index 60a0f123..60772625 100644 --- a/test/test_automated_install.py +++ b/test/test_automated_install.py @@ -402,70 +402,6 @@ def test_FTL_binary_installed_and_responsive_no_errors(Pihole): # assert '644 /run/pihole-FTL.pid' in support_files.stdout # assert '644 /var/log/pihole-FTL.log' in support_files.stdout -def test_FTL_telnet_version(Pihole): - ''' confirms FTL binary is copied and functional in installed location and through telnet ''' - FTLtest = Pihole.run(''' - source /opt/pihole/basic-install.sh - source /etc/.pihole/test/FTL-test.sh - FTL_prepare_files - FTLdetect - pihole-FTL - sleep 1 - FTL_get_version - ''') - assert 'version' in FTLtest.stdout - assert 'tag' in FTLtest.stdout - assert 'branch' in FTLtest.stdout - assert 'date' in FTLtest.stdout - -def test_FTL_telnet_statistics(Pihole): - ''' confirms FTL binary is copied and functional in installed location and through telnet ''' - FTLtest = Pihole.run(''' - source /opt/pihole/basic-install.sh - source /etc/.pihole/test/FTL-test.sh - FTL_prepare_files - FTLdetect - pihole-FTL - sleep 1 - FTL_get_stats - ''') - assert 'domains_being_blocked' in FTLtest.stdout - assert 'dns_queries_today 5' in FTLtest.stdout - assert 'unique_domains 4' in FTLtest.stdout - assert 'queries_forwarded 3' in FTLtest.stdout - assert 'queries_cached 2' in FTLtest.stdout - -def test_FTL_telnet_top_clients(Pihole): - ''' confirms FTL binary is copied and functional in installed location and through telnet ''' - FTLtest = Pihole.run(''' - source /opt/pihole/basic-install.sh - source /etc/.pihole/test/FTL-test.sh - FTL_prepare_files - FTLdetect - pihole-FTL - sleep 1 - FTL_get_top_clients - ''') - assert '0 2 192.168.2.208' in FTLtest.stdout - assert '1 2 127.0.0.1' in FTLtest.stdout - assert '2 1 10.8.0.2' in FTLtest.stdout - -def test_FTL_telnet_top_domains(Pihole): - ''' confirms FTL binary is copied and functional in installed location and through telnet ''' - FTLtest = Pihole.run(''' - source /opt/pihole/basic-install.sh - source /etc/.pihole/test/FTL-test.sh - FTL_prepare_files - FTLdetect - pihole-FTL - sleep 1 - FTL_get_top_domains - ''') - assert '0 2 play.google.com' in FTLtest.stdout - assert '1 1 pi.hole' in FTLtest.stdout - assert '2 1 checkip.dyndns.org' in FTLtest.stdout - assert '3 1 raspberrypi' in FTLtest.stdout - def test_IPv6_only_link_local(Pihole): ''' confirms IPv6 blocking is disabled for Link-local address ''' # mock ip -6 address to return Link-local address From aff5ff08d55b3a46bf98e0ca649f25895a4211ca Mon Sep 17 00:00:00 2001 From: WaLLy3K Date: Thu, 15 Jun 2017 17:50:05 +1000 Subject: [PATCH 67/85] Trim version output when update is successful (#1527) --- advanced/Scripts/update.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/advanced/Scripts/update.sh b/advanced/Scripts/update.sh index 24b30de4..6aef183b 100755 --- a/advanced/Scripts/update.sh +++ b/advanced/Scripts/update.sh @@ -197,21 +197,21 @@ main() { if [[ "${web_update}" == true ]]; then web_version_current="$(/usr/local/bin/pihole version --admin --current)" echo ":::" - echo "::: Web Admin version is now at ${web_version_current}" + echo "::: 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'" fi if [[ "${core_update}" == true ]]; then pihole_version_current="$(/usr/local/bin/pihole version --pihole --current)" echo ":::" - echo "::: Pi-hole version is now at ${pihole_version_current}" + echo "::: 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'" fi if [[ ${FTL_update} == true ]]; then - FTL_version_current="$(/usr/bin/pihole-FTL tag)" + FTL_version_current="$(/usr/local/bin/pihole version --ftl --current)" echo ":::" - echo "::: FTL version is now at ${FTL_version_current}" + echo "::: FTL version is now at ${FTL_version_current/* v/v}}" start_service pihole-FTL enable_service pihole-FTL fi From 54a88ab5ab7fcc1ec440677ed9a6eec67d52fa23 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 08:43:05 +0200 Subject: [PATCH 68/85] Change ownership of /etc/pihole to user/group pihole. Fixes #1529 (#1530) --- advanced/pihole-FTL.service | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/advanced/pihole-FTL.service b/advanced/pihole-FTL.service index 30cd140f..627fad8c 100644 --- a/advanced/pihole-FTL.service +++ b/advanced/pihole-FTL.service @@ -26,7 +26,7 @@ start() { echo "pihole-FTL is already running" else touch /var/log/pihole-FTL.log /run/pihole-FTL.pid /run/pihole-FTL.port - chown pihole:pihole /var/log/pihole-FTL.log /run/pihole-FTL.pid /run/pihole-FTL.port + chown pihole:pihole /var/log/pihole-FTL.log /run/pihole-FTL.pid /run/pihole-FTL.port /etc/pihole chmod 0644 /var/log/pihole-FTL.log /run/pihole-FTL.pid /run/pihole-FTL.port su -s /bin/sh -c "/usr/bin/pihole-FTL" "$FTLUSER" echo From 3d7582faec8232e15dccf94909fc1416794915f3 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 08:54:26 +0200 Subject: [PATCH 69/85] Delete temporary files after installing the FTL binary. Fixes #1525 --- automated install/basic-install.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index e8b28f62..053e04ba 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -1277,6 +1277,7 @@ FTLinstall() { echo -n "transferred... " stop_service pihole-FTL &> /dev/null install -T -m 0755 /tmp/${binary} /usr/bin/pihole-FTL + rm /tmp/${binary} /tmp/${binary}.sha1 cd "${orig_dir}" install -T -m 0755 "${PI_HOLE_LOCAL_REPO}/advanced/pihole-FTL.service" "/etc/init.d/pihole-FTL" echo "done." From b32096b16e3a7d81f44752cf41547d98a315b61c Mon Sep 17 00:00:00 2001 From: Dan Schaper Date: Sat, 17 Jun 2017 03:59:27 -0700 Subject: [PATCH 70/85] Change from admin to approvers teams --- .pullapprove.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pullapprove.yml b/.pullapprove.yml index 39566b34..6beb4d34 100644 --- a/.pullapprove.yml +++ b/.pullapprove.yml @@ -35,4 +35,4 @@ groups: - master required: 4 teams: - - admin + - approvers From 0283a1ab74f7a404b96cf28fd055e5077f9b248d Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 13:50:10 +0200 Subject: [PATCH 71/85] Introduce new file black.list for blacklist content --- advanced/01-pihole.conf | 1 + gravity.sh | 57 ++++++++++++++++++++++++----------------- 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/advanced/01-pihole.conf b/advanced/01-pihole.conf index 1b157f88..79735c15 100644 --- a/advanced/01-pihole.conf +++ b/advanced/01-pihole.conf @@ -22,6 +22,7 @@ addn-hosts=/etc/pihole/gravity.list addn-hosts=/etc/pihole/local.list +addn-hosts=/etc/pihole/black.list domain-needed diff --git a/gravity.sh b/gravity.sh index a5231d5e..cb6768e4 100755 --- a/gravity.sh +++ b/gravity.sh @@ -54,6 +54,7 @@ IPV6_ADDRESS=${IPV6_ADDRESS} basename=pihole piholeDir=/etc/${basename} adList=${piholeDir}/gravity.list +blackList=${piholeDir}/black.list localList=${piholeDir}/local.list justDomainsExtension=domains matterAndLight=${basename}.0.matterandlight.txt @@ -236,7 +237,7 @@ gravity_Blacklist() { numBlacklisted=$(wc -l < "${blacklistFile}") plural=; [[ "$numBlacklisted" != "1" ]] && plural=s echo -n "::: Blacklisting $numBlacklisted domain${plural}..." - cat ${blacklistFile} >> ${piholeDir}/${eventHorizon} + cat "${blacklistFile}" > "${blackList}.tmp" echo " done!" else echo "::: Nothing to blacklist!" @@ -299,6 +300,23 @@ gravity_unique() { echo "::: $numberOf unique domains trapped in the event horizon." } +gravity_doHostFormat() { + # Check vars from setupVars.conf to see if we're using IPv4, IPv6, Or both. + if [[ -n "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then + # Both IPv4 and IPv6 + cat "${1}" | awk -v ipv4addr="$IPV4_ADDRESS" -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> "${2}" + elif [[ -n "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then + # Only IPv4 + cat "${1}" | awk -v ipv4addr="$IPV4_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0}' >> "${2}" + elif [[ -z "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then + # Only IPv6 + cat "${1}" | awk -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv6addr" "$0}' >> "${2}" + elif [[ -z "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then + echo "::: No IP Values found! Please run 'pihole -r' and choose reconfigure to restore values" + exit 1 + fi +} + gravity_hostFormat() { # Format domain list as "192.168.x.x domain.com" echo -n "::: Formatting domains into a HOSTS file..." @@ -310,32 +328,23 @@ gravity_hostFormat() { else echo "::: Error: Unable to determine fully qualified domain name of host" fi - # Check vars from setupVars.conf to see if we're using IPv4, IPv6, Or both. - if [[ -n "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then - echo -e "${IPV4_ADDRESS} ${hostname}\n${IPV6_ADDRESS} ${hostname}\n${IPV4_ADDRESS} pi.hole\n${IPV6_ADDRESS} pi.hole" > ${localList} - # Both IPv4 and IPv6 - cat ${piholeDir}/${eventHorizon} | awk -v ipv4addr="$IPV4_ADDRESS" -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> ${piholeDir}/${accretionDisc} - - elif [[ -n "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then - - echo -e "${IPV4_ADDRESS} ${hostname}\n${IPV4_ADDRESS} pi.hole" > ${localList} - # Only IPv4 - cat ${piholeDir}/${eventHorizon} | awk -v ipv4addr="$IPV4_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0}' >> ${piholeDir}/${accretionDisc} - - elif [[ -z "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then - - echo -e "${IPV6_ADDRESS} ${hostname}\n${IPV6_ADDRESS} pi.hole" > ${localList} - # Only IPv6 - cat ${piholeDir}/${eventHorizon} | awk -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv6addr" "$0}' >> ${piholeDir}/${accretionDisc} - - elif [[ -z "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then - echo "::: No IP Values found! Please run 'pihole -r' and choose reconfigure to restore values" - exit 1 - fi + echo -e "${hostname}\npi.hole" > "${localList}.tmp" + # Copy the file over as /etc/pihole/local.list so dnsmasq can use it + gravity_doHostFormat "${localList}.tmp" "${localList}" + rm "${localList}.tmp" + echo "" > "${piholeDir}/${accretionDisc}" + gravity_doHostFormat "${piholeDir}/${eventHorizon}" "${piholeDir}/${accretionDisc}" # Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it - cp ${piholeDir}/${accretionDisc} ${adList} + cp "${piholeDir}/${accretionDisc}" "${adList}" + rm "${piholeDir}/${accretionDisc}" + + echo -e "" > "${blackList}.tmp" + gravity_doHostFormat "${blackList}.tmp" "${blackList}" + # Copy the file over as /etc/pihole/black.list so dnsmasq can use it + cp "${blackList}.tmp" "${blackList}" + rm "${blackList}.tmp" echo " done!" } From 0a9c2341272d45dd8b161a24d23cc5fe36a50d0c Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 13:57:27 +0200 Subject: [PATCH 72/85] Add "pihole -g -b" to *only* update black.list (saves a bunch of time when adding/changing only blacklisted files - won'tdownload lal lists, but only processes the blacklist and restars dnsmasq) --- gravity.sh | 47 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/gravity.sh b/gravity.sh index cb6768e4..2b860183 100755 --- a/gravity.sh +++ b/gravity.sh @@ -317,9 +317,8 @@ gravity_doHostFormat() { fi } -gravity_hostFormat() { +gravity_hostFormatLocal() { # Format domain list as "192.168.x.x domain.com" - echo -n "::: Formatting domains into a HOSTS file..." if [[ -f /etc/hostname ]]; then hostname=$( "${piholeDir}/${accretionDisc}" gravity_doHostFormat "${piholeDir}/${eventHorizon}" "${piholeDir}/${accretionDisc}" # Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it cp "${piholeDir}/${accretionDisc}" "${adList}" rm "${piholeDir}/${accretionDisc}" +} +gravity_hostFormatBlack() { + # Format domain list as "192.168.x.x domain.com" echo -e "" > "${blackList}.tmp" gravity_doHostFormat "${blackList}.tmp" "${blackList}" # Copy the file over as /etc/pihole/black.list so dnsmasq can use it cp "${blackList}.tmp" "${blackList}" rm "${blackList}.tmp" - echo " done!" } # blackbody - remove any remnant files from script processes @@ -386,11 +390,6 @@ gravity_advanced() { } gravity_reload() { - #Clear no longer needed files... - echo ":::" - echo -n "::: Cleaning up un-needed files..." - rm ${piholeDir}/pihole.*.txt - echo " done!" # Reload hosts file echo ":::" @@ -411,6 +410,7 @@ for var in "$@"; do "-f" | "--force" ) forceGrav=true;; "-h" | "--help" ) helpFunc;; "-sd" | "--skip-download" ) skipDownload=true;; + "-b" | "--blacklist-only" ) blackListOnly=true;; esac done @@ -420,22 +420,39 @@ if [[ "${forceGrav}" == true ]]; then echo " done!" fi -gravity_collapse -gravity_spinup -if [[ "${skipDownload}" == false ]]; then +if [[ ! "${blackListOnly}" == true ]]; then + gravity_collapse + gravity_spinup + if [[ "${skipDownload}" == false ]]; then gravity_Schwarzchild gravity_advanced -else + else echo "::: Using cached Event Horizon list..." numberOf=$(wc -l < ${piholeDir}/${preEventHorizon}) - echo "::: $numberOf unique domains trapped in the event horizon." + echo "::: $numberOf unique domains trapped in the event horizon." + fi + gravity_Whitelist fi -gravity_Whitelist gravity_Blacklist gravity_Wildcard -gravity_hostFormat +echo -n "::: Formatting domains into a HOSTS file..." +if [[ ! "${blackListOnly}" == true ]]; then + gravity_hostFormatLocal + gravity_hostFormatGravity +fi +gravity_hostFormatBlack +echo " done!" + gravity_blackbody +if [[ ! "${blackListOnly}" == true ]]; then + #Clear no longer needed files... + echo ":::" + echo -n "::: Cleaning up un-needed files..." + rm ${piholeDir}/pihole.*.txt + echo " done!" +fi + gravity_reload "${PIHOLE_COMMAND}" status From 92e691408f58e6ae8fd3eae7acfcfd0175245abc Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 14:14:07 +0200 Subject: [PATCH 73/85] Remove useless cat --- gravity.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/gravity.sh b/gravity.sh index 2b860183..558cbd18 100755 --- a/gravity.sh +++ b/gravity.sh @@ -304,13 +304,13 @@ gravity_doHostFormat() { # Check vars from setupVars.conf to see if we're using IPv4, IPv6, Or both. if [[ -n "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then # Both IPv4 and IPv6 - cat "${1}" | awk -v ipv4addr="$IPV4_ADDRESS" -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0"\n"ipv6addr" "$0}' >> "${2}" + 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 # Only IPv4 - cat "${1}" | awk -v ipv4addr="$IPV4_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0}' >> "${2}" + awk -v ipv4addr="$IPV4_ADDRESS" '{sub(/\r$/,""); print ipv4addr" "$0}' >> "${2}" < "${1}" elif [[ -z "${IPV4_ADDRESS}" && -n "${IPV6_ADDRESS}" ]];then # Only IPv6 - cat "${1}" | awk -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv6addr" "$0}' >> "${2}" + awk -v ipv6addr="$IPV6_ADDRESS" '{sub(/\r$/,""); print ipv6addr" "$0}' >> "${2}" < "${1}" elif [[ -z "${IPV4_ADDRESS}" && -z "${IPV6_ADDRESS}" ]];then echo "::: No IP Values found! Please run 'pihole -r' and choose reconfigure to restore values" exit 1 @@ -330,6 +330,7 @@ gravity_hostFormatLocal() { echo -e "${hostname}\npi.hole" > "${localList}.tmp" # Copy the file over as /etc/pihole/local.list so dnsmasq can use it + rm "${localList}" gravity_doHostFormat "${localList}.tmp" "${localList}" rm "${localList}.tmp" } From 8bad56e89799f05d64d30d367361e9814b48f03c Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 14:24:30 +0200 Subject: [PATCH 74/85] Improve displayed messages and overall logic --- gravity.sh | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/gravity.sh b/gravity.sh index 558cbd18..f333b706 100755 --- a/gravity.sh +++ b/gravity.sh @@ -236,9 +236,7 @@ gravity_Blacklist() { if [[ -f "${blacklistFile}" ]]; then numBlacklisted=$(wc -l < "${blacklistFile}") plural=; [[ "$numBlacklisted" != "1" ]] && plural=s - echo -n "::: Blacklisting $numBlacklisted domain${plural}..." - cat "${blacklistFile}" > "${blackList}.tmp" - echo " done!" + echo "::: Exact blocked domain${plural}: $numBlacklisted" else echo "::: Nothing to blacklist!" fi @@ -345,12 +343,16 @@ gravity_hostFormatGravity() { } gravity_hostFormatBlack() { - # Format domain list as "192.168.x.x domain.com" - echo -e "" > "${blackList}.tmp" - gravity_doHostFormat "${blackList}.tmp" "${blackList}" - # Copy the file over as /etc/pihole/black.list so dnsmasq can use it - cp "${blackList}.tmp" "${blackList}" - rm "${blackList}.tmp" + if [[ -f "${blacklistFile}" ]]; then + numBlacklisted=$(wc -l < "${blacklistFile}") + # Format domain list as "192.168.x.x domain.com" + gravity_doHostFormat "${blacklistFile}" "${blackList}.tmp" + # Copy the file over as /etc/pihole/black.list so dnsmasq can use it + cp "${blackList}.tmp" "${blackList}" + rm "${blackList}.tmp" + else + echo "::: Nothing to blacklist!" + fi } # blackbody - remove any remnant files from script processes From e4cc5b3847314235f88953835fdbae2aea7adb70 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sat, 17 Jun 2017 14:49:02 +0200 Subject: [PATCH 75/85] Disable black.list on "pihole disable" --- pihole | 1 + 1 file changed, 1 insertion(+) diff --git a/pihole b/pihole index f2bc7000..055d6bce 100755 --- a/pihole +++ b/pihole @@ -193,6 +193,7 @@ Time: elif [[ "${1}" == "0" ]]; then # 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\/black.list/#addn-hosts=\/etc\/pihole\/black.list/' /etc/dnsmasq.d/01-pihole.conf if [[ -e "$wildcardlist" ]]; then mv "$wildcardlist" "/etc/pihole/wildcard.list" fi From 05798fe07a363bc1b25e89396efec74b3abc6ace Mon Sep 17 00:00:00 2001 From: DL6ER Date: Mon, 19 Jun 2017 20:21:47 +0200 Subject: [PATCH 76/85] cp + rm === mv (well, almost) --- gravity.sh | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/gravity.sh b/gravity.sh index f333b706..285ce5c3 100755 --- a/gravity.sh +++ b/gravity.sh @@ -338,8 +338,7 @@ gravity_hostFormatGravity() { echo "" > "${piholeDir}/${accretionDisc}" gravity_doHostFormat "${piholeDir}/${eventHorizon}" "${piholeDir}/${accretionDisc}" # Copy the file over as /etc/pihole/gravity.list so dnsmasq can use it - cp "${piholeDir}/${accretionDisc}" "${adList}" - rm "${piholeDir}/${accretionDisc}" + mv "${piholeDir}/${accretionDisc}" "${adList}" } gravity_hostFormatBlack() { @@ -348,8 +347,7 @@ gravity_hostFormatBlack() { # Format domain list as "192.168.x.x domain.com" gravity_doHostFormat "${blacklistFile}" "${blackList}.tmp" # Copy the file over as /etc/pihole/black.list so dnsmasq can use it - cp "${blackList}.tmp" "${blackList}" - rm "${blackList}.tmp" + mv "${blackList}.tmp" "${blackList}" else echo "::: Nothing to blacklist!" fi From 536585b8460defd5de88cec786808e26c410408e Mon Sep 17 00:00:00 2001 From: Adam Warner Date: Wed, 21 Jun 2017 12:49:05 +0100 Subject: [PATCH 77/85] 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" --- advanced/Scripts/COL_TABLE | 28 ++ advanced/Scripts/list.sh | 112 +++--- advanced/Scripts/piholeCheckout.sh | 135 ++++--- advanced/Scripts/piholeLogFlush.sh | 7 +- advanced/Scripts/update.sh | 92 ++--- advanced/Scripts/webpage.sh | 37 +- automated install/basic-install.sh | 537 +++++++++++++++------------ automated install/uninstall.sh | 138 ++++--- gravity.sh | 565 +++++++++++++++-------------- pihole | 107 ++++-- test/test_automated_install.py | 110 ++++-- 11 files changed, 1076 insertions(+), 792 deletions(-) create mode 100644 advanced/Scripts/COL_TABLE diff --git a/advanced/Scripts/COL_TABLE b/advanced/Scripts/COL_TABLE new file mode 100644 index 00000000..20dd98b0 --- /dev/null +++ b/advanced/Scripts/COL_TABLE @@ -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" diff --git a/advanced/Scripts/list.sh b/advanced/Scripts/list.sh index 308e1f5e..9d587296 100755 --- a/advanced/Scripts/list.sh +++ b/advanced/Scripts/list.sh @@ -24,6 +24,10 @@ domToRemoveList=() listMain="" listAlt="" +colfile="/opt/pihole/COL_TABLE" +source ${colfile} + + helpFunc() { if [[ "${listMain}" == "${whitelist}" ]]; then param="w" @@ -64,8 +68,9 @@ HandleOther() { # 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}/') 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 + echo -e " ${TICK} $1 is a valid domain name!" domList=("${domList[@]}" ${validDomain}) fi } @@ -93,6 +98,10 @@ PoplistFile() { AddDomain() { list="$2" domain=$(EscapeRegexp "$1") + + [[ "${list}" == "${whitelist}" ]] && listname="whitelist" + [[ "${list}" == "${blacklist}" ]] && listname="blacklist" + [[ "${list}" == "${wildcardlist}" ]] && listname="wildcard blacklist" if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then bool=true @@ -102,14 +111,14 @@ AddDomain() { if [[ "${bool}" == false ]]; then # Domain not found in the whitelist file, add it! if [[ "${verbose}" == true ]]; then - echo "::: Adding $1 to $list..." + echo -e " ${INFO} Adding $1 to $listname..." fi reload=true # Add it to the list we want to add it to echo "$1" >> "${list}" else 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 elif [[ "${list}" == "${wildcardlist}" ]]; then @@ -124,7 +133,7 @@ AddDomain() { if [[ "${bool}" == false ]]; then if [[ "${verbose}" == true ]]; then - echo "::: Adding $1 to wildcard blacklist..." + echo -e " ${INFO} Adding $1 to wildcard blacklist..." fi reload=true echo "address=/$1/${IPV4_ADDRESS}" >> "${wildcardlist}" @@ -133,67 +142,78 @@ AddDomain() { fi else 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 } RemoveDomain() { - list="$2" - domain=$(EscapeRegexp "$1") + list="$2" + domain=$(EscapeRegexp "$1") + + [[ "${list}" == "${whitelist}" ]] && listname="whitelist" + [[ "${list}" == "${blacklist}" ]] && listname="blacklist" + [[ "${list}" == "${wildcardlist}" ]] && listname="wildcard blacklist" - if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then - bool=true - # Is it in the list? Logic follows that if its whitelisted it should not be blacklisted and vice versa - grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false - if [[ "${bool}" == true ]]; then - # Remove it from the other one - echo "::: Removing $1 from $list..." - # /I flag: search case-insensitive - sed -i "/${domain}/Id" "${list}" - reload=true - else - if [[ "${verbose}" == true ]]; then - echo "::: ${1} does not exist in ${list}, no need to remove!" - fi - fi - elif [[ "${list}" == "${wildcardlist}" ]]; then - bool=true - # Is it in the list? - grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false - if [[ "${bool}" == true ]]; then - # Remove it from the other one - echo "::: Removing $1 from $list..." - # /I flag: search case-insensitive - sed -i "/address=\/${domain}/Id" "${list}" - reload=true - else - if [[ "${verbose}" == true ]]; then - echo "::: ${1} does not exist in ${list}, no need to remove!" - fi + if [[ "${list}" == "${whitelist}" || "${list}" == "${blacklist}" ]]; then + bool=true + # Is it in the list? Logic follows that if its whitelisted it should not be blacklisted and vice versa + grep -Ex -q "${domain}" "${list}" > /dev/null 2>&1 || bool=false + if [[ "${bool}" == true ]]; then + # Remove it from the other one + echo -e " ${INFO} Removing $1 from $listname..." + # /I flag: search case-insensitive + sed -i "/${domain}/Id" "${list}" + 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 + bool=true + # Is it in the list? + grep -e "address=\/${domain}\/" "${wildcardlist}" > /dev/null 2>&1 || bool=false + if [[ "${bool}" == true ]]; then + # Remove it from the other one + echo -e " ${INFO} Removing $1 from $listname..." + # /I flag: search case-insensitive + sed -i "/address=\/${domain}/Id" "${list}" + reload=true + else + if [[ "${verbose}" == true ]]; then + echo -e " ${INFO} ${1} does not exist in ${listname}, no need to remove!" + fi + fi + fi } Reload() { # Reload hosts file + echo "" + echo -e " ${INFO} Updating gravity..." + echo "" pihole -g -sd } Displaylist() { - if [[ "${listMain}" == "${whitelist}" ]]; then - string="gravity resistant domains" + if [[ -f ${listMain} ]]; then + 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 - string="domains caught in the sinkhole" + echo -e " ${COL_LIGHT_RED}${listMain} does not exist!${COL_NC}" 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; } diff --git a/advanced/Scripts/piholeCheckout.sh b/advanced/Scripts/piholeCheckout.sh index e2c0ab11..102db2ba 100644 --- a/advanced/Scripts/piholeCheckout.sh +++ b/advanced/Scripts/piholeCheckout.sh @@ -9,7 +9,8 @@ # Please see LICENSE file for your rights under this license. 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 # 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}" update="false" -# Colour codes -red="\e[1;31m" -def="\e[0m" +coltable="/opt/pihole/COL_TABLE" +source ${coltable} fully_fetch_repo() { # Add upstream branches to shallow clone @@ -41,10 +41,12 @@ fully_fetch_repo() { get_available_branches() { # Return available branches local directory="${1}" + local output cd "${directory}" || return 1 - # Get reachable remote branches - git remote show origin | grep 'tracked' | sed 's/tracked//;s/ //g' + # Get reachable remote branches, but store STDERR as STDOUT variable + output=$( { git remote show origin | grep 'tracked' | sed 's/tracked//;s/ //g'; } 2>&1 ) + echo "$output" return } @@ -72,29 +74,36 @@ checkout_pull_branch() { cd "${directory}" || return 1 oldbranch="$(git symbolic-ref HEAD)" - + 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" 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 } warning1() { 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 -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 case ${response} in [yY][eE][sS]|[yY]) - echo "::: Continuing with branch change." + echo "" return 0 ;; *) - echo "::: Branch change has been cancelled." + echo -e "\n ${INFO} Branch change has been cancelled" return 1 ;; esac @@ -107,24 +116,23 @@ checkout() { # Avoid globbing set -f - #This is unlikely + # This is unlikely if ! is_repo "${PI_HOLE_FILES_DIR}" ; then - echo "::: 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 " ${COL_LIGHT_RED}Error: Core Pi-hole repo is missing from system! + Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}" exit 1; fi if [[ ${INSTALL_WEB} == "true" ]]; then if ! is_repo "${webInterfaceDir}" ; then - echo "::: 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 " ${COL_LIGHT_RED}Error: Web Admin repo is missing from system! + Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}" exit 1; fi fi if [[ -z "${1}" ]]; then - echo "::: No option detected. Please use 'pihole checkout '." - echo "::: Or enter the repository and branch you would like to check out:" - echo "::: 'pihole checkout '" + echo -e " ${COL_LIGHT_RED}Invalid option${COL_NC} + Try 'pihole checkout --help' for more information." exit 1 fi @@ -134,72 +142,91 @@ checkout() { if [[ "${1}" == "dev" ]] ; then # Shortcut to check out development branches - echo "::: Shortcut \"dev\" detected - checking out development / devel branches ..." - echo "::: Pi-hole core" - fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "development" || { echo "Unable to pull Core developement branch"; exit 1; } + echo -e " ${INFO} Shortcut \"dev\" detected - checking out development / devel branches..." + echo -e " ${INFO} Pi-hole core" + fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "development" || { echo " ${CROSS} Unable to pull Core developement branch"; exit 1; } if [[ ${INSTALL_WEB} == "true" ]]; then - echo "::: Web interface" - fetch_checkout_pull_branch "${webInterfaceDir}" "devel" || { echo "Unable to pull Web development branch"; exit 1; } + echo -e " ${INFO} Web interface" + fetch_checkout_pull_branch "${webInterfaceDir}" "devel" || { echo " ${CROSS} Unable to pull Web development branch"; exit 1; } fi - echo "::: done!" + echo -e " ${TICK} Pi-hole core" elif [[ "${1}" == "master" ]] ; then # Shortcut to check out master branches - echo "::: Shortcut \"master\" detected - checking out master branches ..." - echo "::: Pi-hole core" - fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "master" || { echo "Unable to pull Core master branch"; exit 1; } + echo -e " ${INFO} Shortcut \"master\" detected - checking out master branches..." + echo -e " ${INFO} Pi-hole core" + fetch_checkout_pull_branch "${PI_HOLE_FILES_DIR}" "master" || { echo " ${CROSS} Unable to pull Core master branch"; exit 1; } if [[ ${INSTALL_WEB} == "true" ]]; then - echo "::: Web interface" - fetch_checkout_pull_branch "${webInterfaceDir}" "master" || { echo "Unable to pull web master branch"; exit 1; } + echo -e " ${INFO} Web interface" + fetch_checkout_pull_branch "${webInterfaceDir}" "master" || { echo " ${CROSS} Unable to pull Web master branch"; exit 1; } fi - echo "::: done!" + echo -e " ${TICK} Web interface" + 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 - echo "::: Fetching all branches for Pi-hole core repo failed!" + echo -e " ${CROSS} $str" exit 1 fi corebranches=($(get_available_branches "${PI_HOLE_FILES_DIR}")) - echo " done!" - echo "::: ${#corebranches[@]} branches available" - echo ":::" - # Have to user chosing the branch he wants + + if [[ "${corebranches[@]}" == *"master"* ]]; then + echo -e "${OVER} ${TICK} $str + ${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 - echo "::: Requested branch \"${2}\" is not available!" - echo "::: Available branches for core are:" - for e in "${corebranches[@]}"; do echo "::: $e"; done + echo -e " ${INFO} Requested branch \"${2}\" is not available" + echo -e " ${INFO} Available branches for Core are:" + for e in "${corebranches[@]}"; do echo " - $e"; done exit 1 fi checkout_pull_branch "${PI_HOLE_FILES_DIR}" "${2}" - elif [[ "${1}" == "web" && "${INSTALL_WEB}" == "true" ]] ; then - echo -n "::: Fetching remote branches for the web interface from ${webInterfaceGitUrl} ... " + elif [[ "${1}" == "web" ]] && [[ "${INSTALL_WEB}" == "true" ]] ; then + str="Fetching branches from ${webInterfaceGitUrl}" + echo -ne " ${INFO} $str" if ! fully_fetch_repo "${webInterfaceDir}" ; then - echo "::: Fetching all branches for Pi-hole web interface repo failed!" + echo -e " ${CROSS} $str" exit 1 fi webbranches=($(get_available_branches "${webInterfaceDir}")) - echo " done!" - echo "::: ${#webbranches[@]} branches available" - echo ":::" - # Have to user chosing the branch he wants + + if [[ "${corebranches[@]}" == *"master"* ]]; then + echo -e "${OVER} ${TICK} $str + ${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 - echo "::: Requested branch \"${2}\" is not available!" - echo "::: Available branches for web are:" - for e in "${webbranches[@]}"; do echo "::: $e"; done + echo -e " ${INFO} Requested branch \"${2}\" is not available" + echo -e " ${INFO} Available branches for Web Admin are:" + for e in "${webbranches[@]}"; do echo " - $e"; done exit 1 fi checkout_pull_branch "${webInterfaceDir}" "${2}" else - echo "::: Requested option \"${1}\" is not available!" + echo -e " ${INFO} Requested option \"${1}\" is not available" exit 1 fi # Force updating everything 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 exit 0 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 fi fi diff --git a/advanced/Scripts/piholeLogFlush.sh b/advanced/Scripts/piholeLogFlush.sh index cc553b32..2187f3ac 100755 --- a/advanced/Scripts/piholeLogFlush.sh +++ b/advanced/Scripts/piholeLogFlush.sh @@ -8,8 +8,11 @@ # This file is copyright under the latest version of the EUPL. # Please see LICENSE file for your rights under this license. +colfile="/opt/pihole/COL_TABLE" +source ${colfile} + if [[ "$@" != *"quiet"* ]]; then - echo -n "::: Flushing /var/log/pihole.log ..." + echo -ne " ${INFO} Flushing /var/log/pihole.log ..." fi if [[ "$@" == *"once"* ]]; then # Nightly logrotation @@ -41,5 +44,5 @@ else fi if [[ "$@" != *"quiet"* ]]; then - echo "... done!" + echo -e "${OVER} ${TICK} Flushed /var/log/pihole.log" fi diff --git a/advanced/Scripts/update.sh b/advanced/Scripts/update.sh index 6aef183b..e8155f1a 100755 --- a/advanced/Scripts/update.sh +++ b/advanced/Scripts/update.sh @@ -22,6 +22,10 @@ readonly PI_HOLE_FILES_DIR="/etc/.pihole" PH_TEST=true source ${PI_HOLE_FILES_DIR}/automated\ install/basic-install.sh +colfile="/opt/pihole/COL_TABLE" +source ${colfile} + + # is_repo() sourced from basic-install.sh # make_repo() sourced from basic-install.sh # update_repo() source from basic-install.sh @@ -49,14 +53,14 @@ GitCheckUpdateAvail() { REMOTE="$(git rev-parse @{upstream})" if [[ ${#LOCAL} == 0 ]]; then - echo "::: Error: Local revision could not be obtained, ask Pi-hole support." - echo "::: Additional debugging output:" + echo -e " ${COL_LIGHT_RED}Error: Local revision could not be obtained, ask Pi-hole support." + echo -e " Additional debugging output:${COL_NC}" git status exit fi if [[ ${#REMOTE} == 0 ]]; then - echo "::: Error: Remote revision could not be obtained, ask Pi-hole support." - echo "::: Additional debugging output:" + echo -e " ${COL_LIGHT_RED}Error: Remote revision could not be obtained, ask Pi-hole support." + echo -e " Additional debugging output:${COL_NC}" git status exit fi @@ -94,52 +98,52 @@ main() { #This is unlikely if ! is_repo "${PI_HOLE_FILES_DIR}" ; then - echo "::: 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 " ${COL_LIGHT_RED}Critical Error: Core Pi-hole repo is missing from system!" + echo -e " Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}" exit 1; fi - echo "::: Checking for updates..." + echo -e " ${INFO} Checking for updates..." if GitCheckUpdateAvail "${PI_HOLE_FILES_DIR}" ; then core_update=true - echo "::: Pi-hole Core: update available" + echo -e " ${INFO} Pi-hole Core:\t${COL_YELLOW}update available${COL_NC}" else 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 if FTLcheckUpdate ; then FTL_update=true - echo "::: FTL: update available" + echo -e " ${INFO} FTL:\t\t${COL_YELLOW}update available${COL_NC}" else FTL_update=false - echo "::: FTL: up to date" + echo -e " ${INFO} FTL:\t\t${COL_LIGHT_GREEN}up to date${COL_NC}" fi - + # Logic: Don't update FTL when there is a core update available # since the core update will run the installer which will itself # re-install (i.e. update) FTL if ${FTL_update} && ! ${core_update}; then - echo ":::" - echo "::: FTL out of date" + echo "" + echo -e " ${INFO} FTL out of date" FTLdetect - echo ":::" + echo "" fi if [[ ${INSTALL_WEB} == true ]]; then if ! is_repo "${ADMIN_INTERFACE_DIR}" ; then - echo "::: 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 " ${COL_LIGHT_RED}Critical Error: Web Admin repo is missing from system!" + echo -e " Please re-run install script from https://github.com/pi-hole/pi-hole${COL_NC}" exit 1; fi if GitCheckUpdateAvail "${ADMIN_INTERFACE_DIR}" ; then web_update=true - echo "::: Web Interface: update available" + echo -e " ${INFO} Web Interface:\t${COL_YELLOW}update available${COL_NC}" else web_update=false - echo "::: Web Interface: up to date" + echo -e " ${INFO} Web Interface:\t${COL_LIGHT_GREEN}up to date${COL_NC}" fi # Logic @@ -154,64 +158,64 @@ main() { if ! ${core_update} && ! ${web_update} ; then if ! ${FTL_update} ; then - echo ":::" - echo "::: Everything is up to date!" + echo "" + echo -e " ${TICK} Everything is up to date!" exit 0 fi elif ! ${core_update} && ${web_update} ; then - echo ":::" - echo "::: Pi-hole Web Admin files out of date" + echo "" + echo -e " ${INFO} Pi-hole Web Admin files out of date" getGitFiles "${ADMIN_INTERFACE_DIR}" "${ADMIN_INTERFACE_GIT_URL}" elif ${core_update} && ! ${web_update} ; then - echo ":::" - echo "::: Pi-hole core files out of date" + echo "" + echo -e " ${INFO} Pi-hole core files out of date" 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 - echo ":::" - echo "::: Updating Pi-hole core and web admin files" + echo "" + echo -e " ${INFO} Updating Pi-hole core and web admin files" 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 - 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 fi else # Web Admin not installed, so only verify if core is up to date if ! ${core_update}; then if ! ${FTL_update} ; then - echo ":::" - echo "::: Everything is up to date!" + echo "" + echo -e " ${INFO} Everything is up to date!" exit 0 fi else - echo ":::" - echo "::: Pi-hole core files out of date" + echo "" + echo -e " ${INFO} Pi-hole core files out of date" 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 if [[ "${web_update}" == true ]]; then web_version_current="$(/usr/local/bin/pihole version --admin --current)" - echo ":::" - echo "::: 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 "" + echo -e " ${INFO} Web Admin version is now at ${web_version_current/* v/v}" + echo -e " ${INFO} If you had made any changes in '/var/www/html/admin/', they have been stashed using 'git stash'" fi if [[ "${core_update}" == true ]]; then pihole_version_current="$(/usr/local/bin/pihole version --pihole --current)" - echo ":::" - echo "::: 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 "" + echo -e " ${INFO} Pi-hole version is now at ${pihole_version_current/* v/v}" + echo -e " ${INFO} If you had made any changes in '/etc/.pihole/', they have been stashed using 'git stash'" fi if [[ ${FTL_update} == true ]]; then - FTL_version_current="$(/usr/local/bin/pihole version --ftl --current)" - echo ":::" - echo "::: FTL version is now at ${FTL_version_current/* v/v}}" + FTL_version_current="$(/usr/bin/pihole-FTL tag)" + echo "" + echo -e " ${INFO} FTL version is now at ${FTL_version_current/* v/v}" start_service pihole-FTL enable_service pihole-FTL fi diff --git a/advanced/Scripts/webpage.sh b/advanced/Scripts/webpage.sh index 8419aa8d..b05cdbfb 100755 --- a/advanced/Scripts/webpage.sh +++ b/advanced/Scripts/webpage.sh @@ -14,13 +14,17 @@ readonly dhcpconfig="/etc/dnsmasq.d/02-pihole-dhcp.conf" # 03 -> wildcards readonly dhcpstaticconfig="/etc/dnsmasq.d/04-pihole-static-dhcp.conf" +coltable="/opt/pihole/COL_TABLE" +if [[ -f ${coltable} ]]; then + source ${coltable} +fi + helpFunc() { echo "Usage: pihole -a [options] Example: pihole -a -p password Set options for the Admin Console Options: - -f, flush Flush the Pi-hole log -p, password Set Admin Console password -c, celsius Set Celsius as preferred temperature unit -f, fahrenheit Set Fahrenheit as preferred temperature unit @@ -58,6 +62,7 @@ delete_dnsmasq_setting() { SetTemperatureUnit() { change_setting "TEMPERATUREUNIT" "${unit}" + echo -e " ${TICK} Set temperature unit to ${unit}" } HashPassword() { @@ -89,7 +94,7 @@ SetWebPassword() { if [ "${PASSWORD}" == "" ]; then change_setting "WEBPASSWORD" "" - echo "Password Removed" + echo -e " ${TICK} Password Removed" exit 0 fi @@ -101,9 +106,9 @@ SetWebPassword() { hash=$(HashPassword ${PASSWORD}) # Save hash to file change_setting "WEBPASSWORD" "${hash}" - echo "New password set" + echo -e " ${TICK} New password set" 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 fi } @@ -213,11 +218,19 @@ Reboot() { } RestartDNS() { - if [ -x "$(command -v systemctl)" ]; then - systemctl restart dnsmasq &> /dev/null - else - service dnsmasq restart &> /dev/null - fi + local str="Restarting dnsmasq" + echo -ne " ${INFO} ${str}..." + if [[ -x "$(command -v systemctl)" ]]; then + systemctl restart dnsmasq + else + service dnsmasq restart + fi + + if [[ "$?" == 0 ]]; then + echo -e "${OVER} ${TICK} ${str}" + else + echo -e "${OVER} ${CROSS} ${str}" + fi } SetQueryLogOptions() { @@ -404,13 +417,13 @@ Interfaces: fi 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" 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" else - echo "Listening only on interface ${PIHOLE_INTERFACE}" + echo -e " ${INFO} Listening only on interface ${PIHOLE_INTERFACE}" change_setting "DNSMASQ_LISTENING" "single" fi diff --git a/automated install/basic-install.sh b/automated install/basic-install.sh index 053e04ba..10ad7aff 100755 --- a/automated install/basic-install.sh +++ b/automated install/basic-install.sh @@ -22,6 +22,7 @@ tmpLog=/tmp/pihole-install.log instalLogLoc=/etc/pihole/install.log setupVars=/etc/pihole/setupVars.conf lighttpdConfig=/etc/lighttpd/lighttpd.conf +coltable=/opt/pihole/COL_TABLE webInterfaceGitUrl="https://github.com/pi-hole/AdminLTE.git" webInterfaceDir="/var/www/html/admin" @@ -54,15 +55,29 @@ skipSpaceCheck=false reconfigure=false runUnattended=false +if [[ -f ${coltable} ]]; then + source ${coltable} +else + COL_NC='\e[0m' # No Color + COL_LIGHT_GREEN='\e[1;32m' + COL_LIGHT_RED='\e[1;31m' + TICK="[${COL_LIGHT_GREEN}✓${COL_NC}]" + CROSS="[${COL_LIGHT_RED}✗${COL_NC}]" + INFO="[i]" + DONE="${COL_LIGHT_GREEN} done!${COL_NC}" + OVER="\r\033[K" +fi + + show_ascii_berry() { - echo " - .;;,. + echo -e " + ${COL_LIGHT_GREEN}.;;,. .ccccc:,. :cccclll:. ..,, :ccccclll. ;ooodc 'ccll:;ll .oooodc .;cll.;;looo:. - .. ','. + ${COL_LIGHT_RED}.. ','. .',,,,,,'. .',,,,,,,,,,. .',,,,,,,,,,,,.... @@ -75,7 +90,7 @@ show_ascii_berry() { ....',,,,,,,,,,,,. .',,,,,,,,,'. .',,,,,,'. - ..'''. + ..'''.${COL_NC} " } @@ -148,7 +163,7 @@ elif command -v rpm &> /dev/null; then DNSMASQ_USER="nobody" else - echo "OS distribution not supported" + echo -e " ${CROSS} OS distribution not supported" exit fi } @@ -176,14 +191,14 @@ is_repo() { make_repo() { local directory="${1}" local remoteRepo="${2}" - - echo -n "::: Cloning ${remoteRepo} into ${directory}..." + str="Clone ${remoteRepo} into ${directory}" + echo -ne " ${INFO} ${str}..." # Clean out the directory if it exists for git to clone into if [[ -d "${directory}" ]]; then rm -rf "${directory}" fi git clone -q --depth 1 "${remoteRepo}" "${directory}" &> /dev/null || return $? - echo " done!" + echo -e "${OVER} ${TICK} ${str}" return 0 } @@ -191,14 +206,15 @@ update_repo() { local directory="${1}" local curdir + local str="Update repo in ${1}" curdir="${PWD}" cd "${directory}" &> /dev/null || return 1 # Pull the latest commits - echo -n "::: Updating repo in ${1}..." + echo -ne " ${INFO} ${str}..." git stash --all --quiet &> /dev/null || true # Okay for stash failure git clean --force -d || true # Okay for already clean directory git pull --quiet &> /dev/null || return $? - echo " done!" + echo -e "${OVER} ${TICK} ${str}" cd "${curdir}" &> /dev/null || return 1 return 0 } @@ -208,15 +224,16 @@ getGitFiles() { # as arguments 1 and 2 local directory="${1}" local remoteRepo="${2}" - echo ":::" - echo "::: Checking for existing repository..." + local str="Check for existing repository in ${1}" + echo -ne " ${INFO} ${str}..." if is_repo "${directory}"; then - update_repo "${directory}" || { echo "*** Error: Could not update local repository. Contact support."; exit 1; } - echo " done!" + echo -e "${OVER} ${TICK} ${str}" + update_repo "${directory}" || { echo -e "\n ${COL_LIGHT_RED}Error: Could not update local repository. Contact support.${COL_NC}"; exit 1; } else - make_repo "${directory}" "${remoteRepo}" || { echo "Unable to clone repository, please contact support"; exit 1; } - echo " done!" + echo -e "${OVER} ${CROSS} ${str}" + make_repo "${directory}" "${remoteRepo}" || { echo -e "\n ${COL_LIGHT_RED}Error: Could not update local repository. Contact support.${COL_NC}"; exit 1; } fi + echo "" return 0 } @@ -224,9 +241,10 @@ resetRepo() { local directory="${1}" cd "${directory}" &> /dev/null || return 1 - echo -n "::: Resetting repo in ${1}..." + str="Resetting repository within ${1}..." + echo -ne " ${INFO} ${str}" git reset --hard &> /dev/null || return $? - echo " done!" + echo -e "${OVER} ${TICK} ${str}" return 0 } @@ -263,29 +281,35 @@ verifyFreeDiskSpace() { # 50MB is the minimum space needed (45MB install (includes web admin bootstrap/jquery libraries etc) + 5MB one day of logs.) # - Fourdee: Local ensures the variable is only created, and accessible within this function/void. Generally considered a "good" coding practice for non-global variables. - echo "::: Verifying free disk space..." + local str="Disk space check" local required_free_kilobytes=51200 local existing_free_kilobytes=$(df -Pk | grep -m1 '\/$' | awk '{print $4}') # - Unknown free disk space , not a integer if ! [[ "${existing_free_kilobytes}" =~ ^([0-9])+$ ]]; then - echo "::: Unknown free disk space!" - echo "::: We were unable to determine available free disk space on this system." - echo "::: You may override this check and force the installation, however, it is not recommended" - echo "::: To do so, pass the argument '--i_do_not_follow_recommendations' to the install script" - echo "::: eg. curl -L https://install.pi-hole.net | bash /dev/stdin --i_do_not_follow_recommendations" + echo -e " ${CROSS} ${str} + Unknown free disk space! + We were unable to determine available free disk space on this system. + You may override this check, however, it is not recommended + The option '${COL_LIGHT_RED}--i_do_not_follow_recommendations${COL_NC}' can override this + e.g: curl -L https://install.pi-hole.net | bash /dev/stdin ${COL_LIGHT_RED}