use modern shell syntax and fix various warnings

This unifies the codestyle across all shell scripts, and fixes many
warnings reported through shellcheck. Additionally, it improves
readability for everyone wishing to see what is actually going on.
This commit is contained in:
a1346054 2021-08-20 14:19:03 +00:00 committed by goonix
parent 27ed048374
commit f47b320a4a
6 changed files with 129 additions and 134 deletions

View File

@ -20,24 +20,23 @@
# SOFTWARE. # SOFTWARE.
# This function allows you to check if the required tools have been installed. # This function allows you to check if the required tools have been installed.
function check_tool() { check_tool() {
cmd=$1 cmd=$1
if ! command -v "$cmd" &>/dev/null if ! command -v "$cmd" >/dev/null; then
then
echo "$cmd could not be found" echo "$cmd could not be found"
echo "Please install $cmd" echo "Please install $cmd"
exit 1 exit 1
fi fi
} }
# Now we call the function to make sure we can use wg-quick, curl and jq. # Now we call the function to make sure we can use openvpn, curl and jq.
check_tool openvpn
check_tool curl check_tool curl
check_tool jq check_tool jq
check_tool openvpn
# Check if terminal allows output, if yes, define colors for output # Check if terminal allows output, if yes, define colors for output
if test -t 1; then if [[ -t 1 ]]; then
ncolors=$(tput colors) ncolors=$(tput colors)
if test -n "$ncolors" && test "$ncolors" -ge 8; then if [[ -n $ncolors && $ncolors -ge 8 ]]; then
GREEN='\033[0;32m' GREEN='\033[0;32m'
RED='\033[0;31m' RED='\033[0;31m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
@ -51,16 +50,16 @@ fi
# Check if manual PIA OpenVPN connection is already initialized. # Check if manual PIA OpenVPN connection is already initialized.
# Multi-hop is out of the scope of this repo, but you should be able to # Multi-hop is out of the scope of this repo, but you should be able to
# get multi-hop running with both OpenVPN and WireGuard. # get multi-hop running with both OpenVPN and WireGuard.
adapter_check="$( ip a s tun06 2>&1 )" adapter_check=$( ip a s tun06 2>&1 )
should_read="Device \"tun06\" does not exist" should_read="Device \"tun06\" does not exist"
pid_filepath="/opt/piavpn-manual/pia_pid" pid_filepath="/opt/piavpn-manual/pia_pid"
if [[ "$adapter_check" != *"$should_read"* ]]; then if [[ $adapter_check != *"$should_read"* ]]; then
echo -e ${RED}The tun06 adapter already exists, that interface is required echo -e ${RED}The tun06 adapter already exists, that interface is required
echo -e for this configuration.${NC} echo -e for this configuration.${NC}
if [ -f "$pid_filepath" ]; then if [[ -f $pid_filepath ]]; then
old_pid="$( cat "$pid_filepath" )" old_pid=$( cat "$pid_filepath" )
old_pid_name="$( ps -p "$old_pid" -o comm= )" old_pid_name=$( ps -p "$old_pid" -o comm= )
if [[ $old_pid_name == 'openvpn' ]]; then if [[ $old_pid_name == "openvpn" ]]; then
echo echo
echo -e It seems likely that process ${RED}"$old_pid"${NC} is an OpenVPN connection echo -e It seems likely that process ${RED}"$old_pid"${NC} is an OpenVPN connection
echo that was established by using this script. Unless it is closed echo that was established by using this script. Unless it is closed
@ -99,10 +98,10 @@ then
fi fi
# Check if the mandatory environment variables are set. # Check if the mandatory environment variables are set.
if [[ ! $OVPN_SERVER_IP || if [[ -z $OVPN_SERVER_IP ||
! $OVPN_HOSTNAME || -z $OVPN_HOSTNAME ||
! $PIA_TOKEN || -z $PIA_TOKEN ||
! $CONNECTION_SETTINGS ]]; then -z $CONNECTION_SETTINGS ]]; then
echo -e ${RED}'This script requires 4 env vars:' echo -e ${RED}'This script requires 4 env vars:'
echo 'PIA_TOKEN - the token used for authentication' echo 'PIA_TOKEN - the token used for authentication'
echo 'OVPN_SERVER_IP - IP that you want to connect to' echo 'OVPN_SERVER_IP - IP that you want to connect to'
@ -138,8 +137,8 @@ echo -e "${GREEN}OK!${NC}"
IFS='_' IFS='_'
read -ra connection_settings <<< "$CONNECTION_SETTINGS" read -ra connection_settings <<< "$CONNECTION_SETTINGS"
IFS=' ' IFS=' '
protocol="${connection_settings[1]}" protocol=${connection_settings[1]}
encryption="${connection_settings[2]}" encryption=${connection_settings[2]}
prefix_filepath="openvpn_config/standard.ovpn" prefix_filepath="openvpn_config/standard.ovpn"
if [[ $encryption == "strong" ]]; then if [[ $encryption == "strong" ]]; then
@ -161,12 +160,12 @@ else
fi fi
# Create the OpenVPN config based on the settings specified # Create the OpenVPN config based on the settings specified
cat $prefix_filepath > /opt/piavpn-manual/pia.ovpn || exit 1 cat "$prefix_filepath" > /opt/piavpn-manual/pia.ovpn || exit 1
echo remote "$OVPN_SERVER_IP" $port "$protocol" >> /opt/piavpn-manual/pia.ovpn echo "remote $OVPN_SERVER_IP $port $protocol" >> /opt/piavpn-manual/pia.ovpn
# Copy the up/down scripts to /opt/piavpn-manual/ # Copy the up/down scripts to /opt/piavpn-manual/
# based upon use of PIA DNS # based upon use of PIA DNS
if [ "$PIA_DNS" != true ]; then if [[ $PIA_DNS != "true" ]]; then
cp openvpn_config/openvpn_up.sh /opt/piavpn-manual/ cp openvpn_config/openvpn_up.sh /opt/piavpn-manual/
cp openvpn_config/openvpn_down.sh /opt/piavpn-manual/ cp openvpn_config/openvpn_down.sh /opt/piavpn-manual/
echo -e ${RED}This configuration will not use PIA DNS.${NC} echo -e ${RED}This configuration will not use PIA DNS.${NC}
@ -201,8 +200,7 @@ Confirming OpenVPN connection state..."
# Manually adjust the connection_wait_time if needed # Manually adjust the connection_wait_time if needed
connection_wait_time=10 connection_wait_time=10
confirmation="Initialization Sequence Complete" confirmation="Initialization Sequence Complete"
for (( timeout=0; timeout <= connection_wait_time; timeout++ )) for (( timeout=0; timeout <= connection_wait_time; timeout++ )); do
do
sleep 1 sleep 1
if grep -q "$confirmation" /opt/piavpn-manual/debug_info; then if grep -q "$confirmation" /opt/piavpn-manual/debug_info; then
connected=true connected=true
@ -210,11 +208,11 @@ do
fi fi
done done
ovpn_pid="$( cat /opt/piavpn-manual/pia_pid )" ovpn_pid=$( cat /opt/piavpn-manual/pia_pid )
gateway_ip="$( cat /opt/piavpn-manual/route_info )" gateway_ip=$( cat /opt/piavpn-manual/route_info )
# Report and exit if connection was not initialized within 10 seconds. # Report and exit if connection was not initialized within 10 seconds.
if [ "$connected" != true ]; then if [[ $connected != "true" ]]; then
echo -e "${RED}The VPN connection was not established within 10 seconds.${NC}" echo -e "${RED}The VPN connection was not established within 10 seconds.${NC}"
kill "$ovpn_pid" kill "$ovpn_pid"
exit 1 exit 1
@ -234,7 +232,7 @@ To disconnect the VPN, run:
" "
# This section will stop the script if PIA_PF is not set to "true". # This section will stop the script if PIA_PF is not set to "true".
if [ "$PIA_PF" != true ]; then if [[ $PIA_PF != "true" ]]; then
echo If you want to also enable port forwarding, you can start the script: echo If you want to also enable port forwarding, you can start the script:
echo -e $ ${GREEN}PIA_TOKEN="$PIA_TOKEN" \ echo -e $ ${GREEN}PIA_TOKEN="$PIA_TOKEN" \
PF_GATEWAY="$gateway_ip" \ PF_GATEWAY="$gateway_ip" \

View File

@ -20,10 +20,9 @@
# SOFTWARE. # SOFTWARE.
# This function allows you to check if the required tools have been installed. # This function allows you to check if the required tools have been installed.
function check_tool() { check_tool() {
cmd=$1 cmd=$1
if ! command -v "$cmd" &>/dev/null if ! command -v "$cmd" >/dev/null; then
then
echo "$cmd could not be found" echo "$cmd could not be found"
echo "Please install $cmd" echo "Please install $cmd"
exit 1 exit 1
@ -35,9 +34,9 @@ check_tool curl
check_tool jq check_tool jq
# Check if terminal allows output, if yes, define colors for output # Check if terminal allows output, if yes, define colors for output
if test -t 1; then if [[ -t 1 ]]; then
ncolors=$(tput colors) ncolors=$(tput colors)
if test -n "$ncolors" && test "$ncolors" -ge 8; then if [[ -n $ncolors && $ncolors -ge 8 ]]; then
GREEN='\033[0;32m' GREEN='\033[0;32m'
RED='\033[0;31m' RED='\033[0;31m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
@ -62,7 +61,9 @@ then
fi fi
# Check if the mandatory environment variables are set. # Check if the mandatory environment variables are set.
if [[ ! $WG_SERVER_IP || ! $WG_HOSTNAME || ! $PIA_TOKEN ]]; then if [[ -z $WG_SERVER_IP ||
-z $WG_HOSTNAME ||
-z $PIA_TOKEN ]]; then
echo -e ${RED}This script requires 3 env vars: echo -e ${RED}This script requires 3 env vars:
echo WG_SERVER_IP - IP that you want to connect to echo WG_SERVER_IP - IP that you want to connect to
echo WG_HOSTNAME - name of the server, required for ssl echo WG_HOSTNAME - name of the server, required for ssl
@ -80,9 +81,9 @@ if [[ ! $WG_SERVER_IP || ! $WG_HOSTNAME || ! $PIA_TOKEN ]]; then
fi fi
# Create ephemeral wireguard keys, that we don't need to save to disk. # Create ephemeral wireguard keys, that we don't need to save to disk.
privKey="$(wg genkey)" privKey=$(wg genkey)
export privKey export privKey
pubKey="$( echo "$privKey" | wg pubkey)" pubKey=$( echo "$privKey" | wg pubkey)
export pubKey export pubKey
# Authenticate via the PIA WireGuard RESTful API. # Authenticate via the PIA WireGuard RESTful API.
@ -101,7 +102,7 @@ wireguard_json="$(curl -s -G \
export wireguard_json export wireguard_json
# Check if the API returned OK and stop this script if it didn't. # Check if the API returned OK and stop this script if it didn't.
if [ "$(echo "$wireguard_json" | jq -r '.status')" != "OK" ]; then if [[ $(echo "$wireguard_json" | jq -r '.status') != "OK" ]]; then
>&2 echo -e "${RED}Server did not return OK. Stopping now.${NC}" >&2 echo -e "${RED}Server did not return OK. Stopping now.${NC}"
exit 1 exit 1
fi fi
@ -120,8 +121,8 @@ echo
# This uses a PersistentKeepalive of 25 seconds to keep the NAT active # This uses a PersistentKeepalive of 25 seconds to keep the NAT active
# on firewalls. You can remove that line if your network does not # on firewalls. You can remove that line if your network does not
# require it. # require it.
if [ "$PIA_DNS" == true ]; then if [[ $PIA_DNS == "true" ]]; then
dnsServer="$(echo "$wireguard_json" | jq -r '.dns_servers[0]')" dnsServer=$(echo "$wireguard_json" | jq -r '.dns_servers[0]')
echo "Trying to set up DNS to $dnsServer. In case you do not have resolvconf," echo "Trying to set up DNS to $dnsServer. In case you do not have resolvconf,"
echo "this operation will fail and you will not get a VPN. If you have issues," echo "this operation will fail and you will not get a VPN. If you have issues,"
echo "start this script without PIA_DNS." echo "start this script without PIA_DNS."
@ -161,7 +162,7 @@ To disconnect the VPN, run:
" "
# This section will stop the script if PIA_PF is not set to "true". # This section will stop the script if PIA_PF is not set to "true".
if [ "$PIA_PF" != true ]; then if [[ $PIA_PF != "true" ]]; then
echo If you want to also enable port forwarding, you can start the script: echo If you want to also enable port forwarding, you can start the script:
echo -e $ ${GREEN}PIA_TOKEN="$PIA_TOKEN" \ echo -e $ ${GREEN}PIA_TOKEN="$PIA_TOKEN" \
PF_GATEWAY="$WG_SERVER_IP" \ PF_GATEWAY="$WG_SERVER_IP" \

View File

@ -20,10 +20,9 @@
# SOFTWARE. # SOFTWARE.
# This function allows you to check if the required tools have been installed. # This function allows you to check if the required tools have been installed.
function check_tool() { check_tool() {
cmd=$1 cmd=$1
if ! command -v "$cmd" &>/dev/null if ! command -v "$cmd" >/dev/null; then
then
echo "$cmd could not be found" echo "$cmd could not be found"
echo "Please install $cmd" echo "Please install $cmd"
exit 1 exit 1
@ -34,7 +33,7 @@ check_tool curl
check_tool jq check_tool jq
# If the server list has less than 1000 characters, it means curl failed. # If the server list has less than 1000 characters, it means curl failed.
function check_all_region_data() { check_all_region_data() {
echo echo
echo -n "Getting the server list..." echo -n "Getting the server list..."
@ -52,11 +51,11 @@ function check_all_region_data() {
# Get all data for the selected region # Get all data for the selected region
# Exit with code 1 if the REGION_ID provided is invalid # Exit with code 1 if the REGION_ID provided is invalid
function get_selected_region_data() { get_selected_region_data() {
regionData="$( echo "$all_region_data" | regionData="$( echo "$all_region_data" |
jq --arg REGION_ID "$selectedRegion" -r \ jq --arg REGION_ID "$selectedRegion" -r \
'.regions[] | select(.id==$REGION_ID)')" '.regions[] | select(.id==$REGION_ID)')"
if [[ ! $regionData ]]; then if [[ -z $regionData ]]; then
echo -e "${RED}The REGION_ID $selectedRegion is not valid.${NC} echo -e "${RED}The REGION_ID $selectedRegion is not valid.${NC}
" "
exit 1 exit 1
@ -64,9 +63,9 @@ function get_selected_region_data() {
} }
# Check if terminal allows output, if yes, define colors for output # Check if terminal allows output, if yes, define colors for output
if test -t 1; then if [[ -t 1 ]]; then
ncolors=$(tput colors) ncolors=$(tput colors)
if test -n "$ncolors" && test "$ncolors" -ge 8; then if [[ -n $ncolors && $ncolors -ge 8 ]]; then
GREEN='\033[0;32m' GREEN='\033[0;32m'
RED='\033[0;31m' RED='\033[0;31m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
@ -101,16 +100,16 @@ serverlist_url='https://serverlist.piaservers.net/vpninfo/servers/v6'
# It will print a human-readable message to stderr, # It will print a human-readable message to stderr,
# and it will print the variables to stdout # and it will print the variables to stdout
printServerLatency() { printServerLatency() {
serverIP="$1" serverIP=$1
regionID="$2" regionID=$2
regionName="$(echo "${@:3}" | regionName="$(echo "${@:3}" |
sed 's/ false//' | sed 's/true/(geo)/')" sed 's/ false//' | sed 's/true/(geo)/')"
time=$(LC_NUMERIC=en_US.utf8 curl -o /dev/null -s \ time=$(LC_NUMERIC=en_US.utf8 curl -o /dev/null -s \
--connect-timeout "$MAX_LATENCY" \ --connect-timeout "$MAX_LATENCY" \
--write-out "%{time_connect}" \ --write-out "%{time_connect}" \
http://"$serverIP":443) "http://$serverIP:443")
if [ $? -eq 0 ]; then if [[ $? -eq 0 ]]; then
>&2 echo Got latency "${time}"s for region: "$regionName" >&2 echo "Got latency ${time}s for region: $regionName"
echo "$time $regionID $serverIP" echo "$time $regionID $serverIP"
# Write a list of servers with acceptable latency # Write a list of servers with acceptable latency
# to /opt/piavpn-manual/latencyList # to /opt/piavpn-manual/latencyList
@ -122,10 +121,10 @@ printServerLatency() {
export -f printServerLatency export -f printServerLatency
# If a server location or autoconnect isn't specified, set the variable to false/no. # If a server location or autoconnect isn't specified, set the variable to false/no.
if [[ -z "$PREFERRED_REGION" ]]; then if [[ -z $PREFERRED_REGION ]]; then
PREFERRED_REGION=none PREFERRED_REGION=none
fi fi
if [[ -z "$VPN_PROTOCOL" ]]; then if [[ -z $VPN_PROTOCOL ]]; then
VPN_PROTOCOL=no VPN_PROTOCOL=no
fi fi
@ -141,7 +140,7 @@ if [[ $selectedRegion == "none" ]]; then
check_all_region_data check_all_region_data
# Making sure this variable doesn't contain some strange string # Making sure this variable doesn't contain some strange string
if [ "$PIA_PF" != true ]; then if [[ $PIA_PF != "true" ]]; then
PIA_PF="false" PIA_PF="false"
fi fi
@ -165,8 +164,8 @@ if [[ $selectedRegion == "none" ]]; then
sort | head -1 | awk '{ print $2 }')" sort | head -1 | awk '{ print $2 }')"
echo echo
if [ -z "$selectedRegion" ]; then if [[ -z $selectedRegion ]]; then
echo -e ${RED}No region responded within "${MAX_LATENCY}"s, consider using a higher timeout. echo -e "${RED}No region responded within ${MAX_LATENCY}s, consider using a higher timeout."
echo For example, to wait 1 second for each region, inject MAX_LATENCY=1 like this: echo For example, to wait 1 second for each region, inject MAX_LATENCY=1 like this:
echo -e $ MAX_LATENCY=1 ./get_region.sh${NC} echo -e $ MAX_LATENCY=1 ./get_region.sh${NC}
exit 1 exit 1
@ -182,14 +181,14 @@ fi
get_selected_region_data get_selected_region_data
bestServer_meta_IP="$(echo "$regionData" | jq -r '.servers.meta[0].ip')" bestServer_meta_IP=$(echo "$regionData" | jq -r '.servers.meta[0].ip')
bestServer_meta_hostname="$(echo "$regionData" | jq -r '.servers.meta[0].cn')" bestServer_meta_hostname=$(echo "$regionData" | jq -r '.servers.meta[0].cn')
bestServer_WG_IP="$(echo "$regionData" | jq -r '.servers.wg[0].ip')" bestServer_WG_IP=$(echo "$regionData" | jq -r '.servers.wg[0].ip')
bestServer_WG_hostname="$(echo "$regionData" | jq -r '.servers.wg[0].cn')" bestServer_WG_hostname=$(echo "$regionData" | jq -r '.servers.wg[0].cn')
bestServer_OT_IP="$(echo "$regionData" | jq -r '.servers.ovpntcp[0].ip')" bestServer_OT_IP=$(echo "$regionData" | jq -r '.servers.ovpntcp[0].ip')
bestServer_OT_hostname="$(echo "$regionData" | jq -r '.servers.ovpntcp[0].cn')" bestServer_OT_hostname=$(echo "$regionData" | jq -r '.servers.ovpntcp[0].cn')
bestServer_OU_IP="$(echo "$regionData" | jq -r '.servers.ovpnudp[0].ip')" bestServer_OU_IP=$(echo "$regionData" | jq -r '.servers.ovpnudp[0].ip')
bestServer_OU_hostname="$(echo "$regionData" | jq -r '.servers.ovpnudp[0].cn')" bestServer_OU_hostname=$(echo "$regionData" | jq -r '.servers.ovpnudp[0].cn')
if [[ $VPN_PROTOCOL == "no" ]]; then if [[ $VPN_PROTOCOL == "no" ]]; then
@ -232,7 +231,7 @@ else
fi fi
# Connect with WireGuard and clear authentication token file and latencyList # Connect with WireGuard and clear authentication token file and latencyList
if [[ $VPN_PROTOCOL == wireguard ]]; then if [[ $VPN_PROTOCOL == "wireguard" ]]; then
echo The ./get_region.sh script got started with echo The ./get_region.sh script got started with
echo -e ${GREEN}VPN_PROTOCOL=wireguard${NC}, so we will automatically connect to WireGuard, echo -e ${GREEN}VPN_PROTOCOL=wireguard${NC}, so we will automatically connect to WireGuard,
echo by running this command: echo by running this command:

View File

@ -20,29 +20,27 @@
# SOFTWARE. # SOFTWARE.
# This function allows you to check if the required tools have been installed. # This function allows you to check if the required tools have been installed.
function check_tool() { check_tool() {
cmd=$1 cmd=$1
if ! command -v "$cmd" &>/dev/null if ! command -v "$cmd" >/dev/null; then
then
echo "$cmd could not be found" echo "$cmd could not be found"
echo "Please install $cmd" echo "Please install $cmd"
exit 1 exit 1
fi fi
} }
# This function creates a timestamp, to use for setting $TOKEN_EXPIRATION
function timeout_timestamp() {
date +"%c" --date='1 day' # Timestamp 24 hours
}
# Now we call the function to make sure we can use curl and jq. # Now we call the function to make sure we can use curl and jq.
check_tool curl check_tool curl
check_tool jq check_tool jq
# This function creates a timestamp, to use for setting $TOKEN_EXPIRATION
timeout_timestamp() {
date +"%c" --date='1 day' # Timestamp 24 hours
}
# Check if terminal allows output, if yes, define colors for output # Check if terminal allows output, if yes, define colors for output
if test -t 1; then if [[ -t 1 ]]; then
ncolors=$(tput colors) ncolors=$(tput colors)
if test -n "$ncolors" && test "$ncolors" -ge 8; then if [[ -n $ncolors && $ncolors -ge 8 ]]; then
GREEN='\033[0;32m' GREEN='\033[0;32m'
RED='\033[0;31m' RED='\033[0;31m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
@ -61,7 +59,7 @@ fi
mkdir -p /opt/piavpn-manual mkdir -p /opt/piavpn-manual
if [[ ! $PIA_USER || ! $PIA_PASS ]]; then if [[ -z $PIA_USER || -z $PIA_PASS ]]; then
echo If you want this script to automatically get a token from the Meta echo If you want this script to automatically get a token from the Meta
echo service, please add the variables PIA_USER and PIA_PASS. Example: echo service, please add the variables PIA_USER and PIA_PASS. Example:
echo $ PIA_USER=p0123456 PIA_PASS=xxx ./get_token.sh echo $ PIA_USER=p0123456 PIA_PASS=xxx ./get_token.sh
@ -75,7 +73,7 @@ echo -n "Checking login credentials..."
generateTokenResponse=$(curl -s -u "$PIA_USER:$PIA_PASS" \ generateTokenResponse=$(curl -s -u "$PIA_USER:$PIA_PASS" \
"https://privateinternetaccess.com/gtoken/generateToken") "https://privateinternetaccess.com/gtoken/generateToken")
if [ "$(echo "$generateTokenResponse" | jq -r '.status')" != "OK" ]; then if [[ $(echo "$generateTokenResponse" | jq -r '.status') != "OK" ]]; then
echo echo
echo echo
echo -e "${RED}Could not authenticate with the login credentials provided!${NC}" echo -e "${RED}Could not authenticate with the login credentials provided!${NC}"
@ -87,9 +85,9 @@ echo -e ${GREEN}OK!
echo echo
token=$(echo "$generateTokenResponse" | jq -r '.token') token=$(echo "$generateTokenResponse" | jq -r '.token')
tokenExpiration=$(timeout_timestamp) tokenExpiration=$(timeout_timestamp)
echo -e PIA_TOKEN="$token"${NC} echo -e "PIA_TOKEN=$token${NC}"
echo "$token" > /opt/piavpn-manual/token || exit 1 echo "$token" > /opt/piavpn-manual/token || exit 1
echo "$tokenExpiration" >> /opt/piavpn-manual/token echo "$tokenExpiration" >> /opt/piavpn-manual/token
echo echo
echo This token will expire in 24 hours, on "$tokenExpiration". echo "This token will expire in 24 hours, on $tokenExpiration."
echo echo

View File

@ -20,21 +20,20 @@
# SOFTWARE. # SOFTWARE.
# This function allows you to check if the required tools have been installed. # This function allows you to check if the required tools have been installed.
function check_tool() { check_tool() {
cmd=$1 cmd=$1
if ! command -v "$cmd" &>/dev/null if ! command -v "$cmd" >/dev/null; then
then
echo "$cmd could not be found" echo "$cmd could not be found"
echo "Please install $cmd" echo "Please install $cmd"
exit 1 exit 1
fi fi
} }
# Now we call the function to make sure we can use wg-quick, curl and jq. # Now we call the function to make sure we can use curl and jq.
check_tool curl check_tool curl
check_tool jq check_tool jq
# Check if the mandatory environment variables are set. # Check if the mandatory environment variables are set.
if [[ ! $PF_GATEWAY || ! $PIA_TOKEN || ! $PF_HOSTNAME ]]; then if [[ -z $PF_GATEWAY || -z $PIA_TOKEN || -z $PF_HOSTNAME ]]; then
echo This script requires 3 env vars: echo This script requires 3 env vars:
echo PF_GATEWAY - the IP of your gateway echo PF_GATEWAY - the IP of your gateway
echo PF_HOSTNAME - name of the host used for SSL/TLS certificate verification echo PF_HOSTNAME - name of the host used for SSL/TLS certificate verification
@ -48,9 +47,9 @@ exit 1
fi fi
# Check if terminal allows output, if yes, define colors for output # Check if terminal allows output, if yes, define colors for output
if test -t 1; then if [[ -t 1 ]]; then
ncolors=$(tput colors) ncolors=$(tput colors)
if test -n "$ncolors" && test "$ncolors" -ge 8; then if [[ -n $ncolors && $ncolors -ge 8 ]]; then
GREEN='\033[0;32m' GREEN='\033[0;32m'
RED='\033[0;31m' RED='\033[0;31m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
@ -81,7 +80,7 @@ fi
# If you already have a signature, and you would like to re-use that port, # If you already have a signature, and you would like to re-use that port,
# save the payload_and_signature received from your previous request # save the payload_and_signature received from your previous request
# in the env var PAYLOAD_AND_SIGNATURE, and that will be used instead. # in the env var PAYLOAD_AND_SIGNATURE, and that will be used instead.
if [[ ! $PAYLOAD_AND_SIGNATURE ]]; then if [[ -z $PAYLOAD_AND_SIGNATURE ]]; then
echo echo
echo -n "Getting new signature... " echo -n "Getting new signature... "
payload_and_signature="$(curl -s -m 5 \ payload_and_signature="$(curl -s -m 5 \
@ -90,14 +89,14 @@ if [[ ! $PAYLOAD_AND_SIGNATURE ]]; then
-G --data-urlencode "token=${PIA_TOKEN}" \ -G --data-urlencode "token=${PIA_TOKEN}" \
"https://${PF_HOSTNAME}:19999/getSignature")" "https://${PF_HOSTNAME}:19999/getSignature")"
else else
payload_and_signature="$PAYLOAD_AND_SIGNATURE" payload_and_signature=$PAYLOAD_AND_SIGNATURE
echo -n "Checking the payload_and_signature from the env var... " echo -n "Checking the payload_and_signature from the env var... "
fi fi
export payload_and_signature export payload_and_signature
# Check if the payload and the signature are OK. # Check if the payload and the signature are OK.
# If they are not OK, just stop the script. # If they are not OK, just stop the script.
if [ "$(echo "$payload_and_signature" | jq -r '.status')" != "OK" ]; then if [[ $(echo "$payload_and_signature" | jq -r '.status') != "OK" ]]; then
echo -e "${RED}The payload_and_signature variable does not contain an OK status.${NC}" echo -e "${RED}The payload_and_signature variable does not contain an OK status.${NC}"
exit 1 exit 1
fi fi
@ -105,18 +104,18 @@ echo -e "${GREEN}OK!${NC}"
# We need to get the signature out of the previous response. # We need to get the signature out of the previous response.
# The signature will allow the us to bind the port on the server. # The signature will allow the us to bind the port on the server.
signature="$(echo "$payload_and_signature" | jq -r '.signature')" signature=$(echo "$payload_and_signature" | jq -r '.signature')
# The payload has a base64 format. We need to extract it from the # The payload has a base64 format. We need to extract it from the
# previous response and also get the following information out: # previous response and also get the following information out:
# - port: This is the port you got access to # - port: This is the port you got access to
# - expires_at: this is the date+time when the port expires # - expires_at: this is the date+time when the port expires
payload="$(echo "$payload_and_signature" | jq -r '.payload')" payload=$(echo "$payload_and_signature" | jq -r '.payload')
port="$(echo "$payload" | base64 -d | jq -r '.port')" port=$(echo "$payload" | base64 -d | jq -r '.port')
# The port normally expires after 2 months. If you consider # The port normally expires after 2 months. If you consider
# 2 months is not enough for your setup, please open a ticket. # 2 months is not enough for your setup, please open a ticket.
expires_at="$(echo "$payload" | base64 -d | jq -r '.expires_at')" expires_at=$(echo "$payload" | base64 -d | jq -r '.expires_at')
echo -ne " echo -ne "
Signature ${GREEN}$signature${NC} Signature ${GREEN}$signature${NC}
@ -142,7 +141,7 @@ while true; do
# If port did not bind, just exit the script. # If port did not bind, just exit the script.
# This script will exit in 2 months, since the port will expire. # This script will exit in 2 months, since the port will expire.
export bind_port_response export bind_port_response
if [ "$(echo "$bind_port_response" | jq -r '.status')" != "OK" ]; then if [[ $(echo "$bind_port_response" | jq -r '.status') != "OK" ]]; then
echo -e "${RED}The API did not return OK when trying to bind port... Exiting." echo -e "${RED}The API did not return OK when trying to bind port... Exiting."
exit 1 exit 1
fi fi

View File

@ -20,9 +20,9 @@
# SOFTWARE. # SOFTWARE.
# Check if terminal allows output, if yes, define colors for output # Check if terminal allows output, if yes, define colors for output
if test -t 1; then if [[ -t 1 ]]; then
ncolors=$(tput colors) ncolors=$(tput colors)
if test -n "$ncolors" && test "$ncolors" -ge 8; then if [[ -n $ncolors && $ncolors -ge 8 ]]; then
GREEN='\033[0;32m' GREEN='\033[0;32m'
RED='\033[0;31m' RED='\033[0;31m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
@ -52,13 +52,13 @@ while :; do
# Check for in-line definition of $PIA_USER # Check for in-line definition of $PIA_USER
if [[ ! $PIA_USER || $PIA_USER = "" ]]; then if [[ ! $PIA_USER || $PIA_USER = "" ]]; then
echo echo
read -rp "PIA username (p#######): " PIA_USER read -r -p "PIA username (p#######): " PIA_USER
fi fi
# Confirm format of PIA_USER input # Confirm format of PIA_USER input
unPrefix="${PIA_USER:0:1}" unPrefix=${PIA_USER:0:1}
unSuffix="${PIA_USER:1}" unSuffix=${PIA_USER:1}
if [[ -z "$PIA_USER" ]]; then if [[ -z $PIA_USER ]]; then
echo -e "\n${RED}You must provide input.${NC}" echo -e "\n${RED}You must provide input.${NC}"
elif [[ ${#PIA_USER} != 8 ]]; then elif [[ ${#PIA_USER} != 8 ]]; then
echo -e "\n${RED}A PIA username is always 8 characters long.${NC}" echo -e "\n${RED}A PIA username is always 8 characters long.${NC}"
@ -79,12 +79,12 @@ while :; do
if [[ ! $PIA_PASS || $PIA_PASS = "" ]]; then if [[ ! $PIA_PASS || $PIA_PASS = "" ]]; then
echo echo
echo -n "PIA password: " echo -n "PIA password: "
read -rs PIA_PASS read -r -s PIA_PASS
echo echo
fi fi
# Confirm format of PIA_PASS input # Confirm format of PIA_PASS input
if [[ -z "$PIA_PASS" ]]; then if [[ -z $PIA_PASS ]]; then
echo -e "\n${RED}You must provide input.${NC}" echo -e "\n${RED}You must provide input.${NC}"
elif [[ ${#PIA_PASS} -lt 8 ]]; then elif [[ ${#PIA_PASS} -lt 8 ]]; then
echo -e "\n${RED}A PIA password is always a minimum of 8 characters long.${NC}" echo -e "\n${RED}A PIA password is always a minimum of 8 characters long.${NC}"
@ -102,8 +102,8 @@ while :; do
tokenLocation="/opt/piavpn-manual/token" tokenLocation="/opt/piavpn-manual/token"
# If the script failed to generate an authentication token, the script will exit early. # If the script failed to generate an authentication token, the script will exit early.
if [ ! -f "$tokenLocation" ]; then if [[ ! -f $tokenLocation ]]; then
read -pr "Do you want to try again ([N]o/[y]es): " tryAgain read -r -p "Do you want to try again ([N]o/[y]es): " tryAgain
if ! echo "${tryAgain:0:1}" | grep -iq y; then if ! echo "${tryAgain:0:1}" | grep -iq y; then
exit 1 exit 1
fi fi
@ -160,7 +160,7 @@ fi
# Input validation and check for conflicting declarations of AUTOCONNECT and PREFERRED_REGION # Input validation and check for conflicting declarations of AUTOCONNECT and PREFERRED_REGION
# If both variables are set, AUTOCONNECT has superiority and PREFERRED_REGION is ignored # If both variables are set, AUTOCONNECT has superiority and PREFERRED_REGION is ignored
if [[ ! $AUTOCONNECT ]]; then if [[ -z $AUTOCONNECT ]]; then
echo AUTOCONNECT was not declared. echo AUTOCONNECT was not declared.
echo echo
selectServer="ask" selectServer="ask"
@ -179,7 +179,7 @@ else
echo -e "Updated ${GREEN}AUTOCONNECT=$AUTOCONNECT${NC}" echo -e "Updated ${GREEN}AUTOCONNECT=$AUTOCONNECT${NC}"
echo echo
fi fi
if [[ ! $PREFERRED_REGION ]]; then if [[ -z $PREFERRED_REGION ]]; then
echo -e "${GREEN}AUTOCONNECT=true${NC}" echo -e "${GREEN}AUTOCONNECT=true${NC}"
echo echo
else else
@ -196,7 +196,7 @@ fi
while :; do while :; do
if [[ ! $PREFERRED_REGION || $PREFERRED_REGION = "" ]]; then if [[ ! $PREFERRED_REGION || $PREFERRED_REGION = "" ]]; then
# If autoconnect is not set, prompt the user to specify a server or auto-connect to the lowest latency # If autoconnect is not set, prompt the user to specify a server or auto-connect to the lowest latency
if [[ $selectServer = "ask" ]]; then if [[ $selectServer == "ask" ]]; then
echo -n "Do you want to manually select a server, instead of auto-connecting to the echo -n "Do you want to manually select a server, instead of auto-connecting to the
server with the lowest latency ([N]o/[y]es): " server with the lowest latency ([N]o/[y]es): "
read -r selectServer read -r selectServer
@ -230,9 +230,9 @@ For example, you can try 0.2 for 200ms allowed latency.
customLatency=0 customLatency=0
customLatency+=$latencyInput customLatency+=$latencyInput
if [[ -z "$latencyInput" ]]; then if [[ -z $latencyInput ]]; then
break break
elif [[ $latencyInput = 0 ]]; then elif [[ $latencyInput == 0 ]]; then
echo -e "${RED}Latency input must not be zero.${NC}\n" echo -e "${RED}Latency input must not be zero.${NC}\n"
elif ! [[ $customLatency =~ $floatCheck ]]; then elif ! [[ $customLatency =~ $floatCheck ]]; then
echo -e "${RED}Latency input must be numeric.${NC}\n" echo -e "${RED}Latency input must be numeric.${NC}\n"
@ -254,7 +254,7 @@ For example, you can try 0.2 for 200ms allowed latency.
export VPN_PROTOCOL export VPN_PROTOCOL
VPN_PROTOCOL=no ./get_region.sh VPN_PROTOCOL=no ./get_region.sh
if [ -s /opt/piavpn-manual/latencyList ]; then if [[ -s /opt/piavpn-manual/latencyList ]]; then
# Output the ordered list of servers that meet the latency specification $MAX_LATENCY # Output the ordered list of servers that meet the latency specification $MAX_LATENCY
echo -e "Ordered list of servers with latency less than ${GREEN}$MAX_LATENCY${NC} seconds:" echo -e "Ordered list of servers with latency less than ${GREEN}$MAX_LATENCY${NC} seconds:"
i=0 i=0
@ -275,8 +275,8 @@ For example, you can try 0.2 for 200ms allowed latency.
# Receive input to specify the server to connect to manually # Receive input to specify the server to connect to manually
while :; do while :; do
read -pr "Input the number of the server you want to connect to ([1]-[$i]) : " serverSelection read -r -p "Input the number of the server you want to connect to ([1]-[$i]) : " serverSelection
if [[ -z "$serverSelection" ]]; then if [[ -z $serverSelection ]]; then
echo -e "\n${RED}You must provide input.${NC}\n" echo -e "\n${RED}You must provide input.${NC}\n"
elif ! [[ $serverSelection =~ $intCheck ]]; then elif ! [[ $serverSelection =~ $intCheck ]]; then
echo -e "\n${RED}You must enter a number.${NC}\n" echo -e "\n${RED}You must enter a number.${NC}\n"
@ -316,7 +316,7 @@ For example, you can try 0.2 for 200ms allowed latency.
fi fi
done done
if [[ ! $VPN_PROTOCOL ]]; then if [[ -z $VPN_PROTOCOL ]]; then
VPN_PROTOCOL="none" VPN_PROTOCOL="none"
fi fi
# This section asks for user connection preferences # This section asks for user connection preferences
@ -362,7 +362,7 @@ ${NC}"
# Check for the required presence of resolvconf for setting DNS on wireguard connections # Check for the required presence of resolvconf for setting DNS on wireguard connections
setDNS="yes" setDNS="yes"
if ! command -v resolvconf &>/dev/null && [ "$VPN_PROTOCOL" == wireguard ]; then if ! command -v resolvconf &>/dev/null && [[ $VPN_PROTOCOL == "wireguard" ]]; then
echo -e ${RED}The resolvconf package could not be found. echo -e ${RED}The resolvconf package could not be found.
echo This script can not set DNS for you and you will echo This script can not set DNS for you and you will
echo -e need to invoke DNS protection some other way.${NC} echo -e need to invoke DNS protection some other way.${NC}
@ -382,7 +382,7 @@ if [[ $setDNS = "yes" ]]; then
PIA_DNS="false" PIA_DNS="false"
fi fi
fi fi
elif [[ $PIA_DNS != "true" || $setDNS = "no" ]];then elif [[ $PIA_DNS != "true" || $setDNS == "no" ]]; then
PIA_DNS="false" PIA_DNS="false"
fi fi
export PIA_DNS export PIA_DNS