Untitled diff

Created Diff never expires
1 removal
685 lines
1 addition
685 lines
#!/bin/bash
#!/bin/bash


# _______ _ _______ _______ ______ _ _______
# _______ _ _______ _______ ______ _ _______
# ( ____ \|\ /|( ( /|( ____ \( ____ \( ___ \ ( \ ( ____ \
# ( ____ \|\ /|( ( /|( ____ \( ____ \( ___ \ ( \ ( ____ \
# | ( \/| ) ( || \ ( || ( \/| ( \/| ( ) )| ( | ( \/
# | ( \/| ) ( || \ ( || ( \/| ( \/| ( ) )| ( | ( \/
# | (__ | | | || \ | || | | (__ | (__/ / | | | (__
# | (__ | | | || \ | || | | (__ | (__/ / | | | (__
# | __) | | | || (\ \) || | | __) | __ ( | | | __)
# | __) | | | || (\ \) || | | __) | __ ( | | | __)
# | ( | | | || | \ || | | ( | ( \ \ | | | (
# | ( | | | || | \ || | | ( | ( \ \ | | | (
# | ) | (___) || ) \ || (____/\| (____/\| )___) )| (____/\| (____/\
# | ) | (___) || ) \ || (____/\| (____/\| )___) )| (____/\| (____/\
# |/ (_______)|/ )_)(_______/(_______/|/ \___/ (_______/(_______/
# |/ (_______)|/ )_)(_______/(_______/|/ \___/ (_______/(_______/


# Written by: @Funilrys, Nissar Chababy <contact at funilrys dot com>
# Written by: @Funilrys, Nissar Chababy <contact at funilrys dot com>
# GitHub : https://github.com/funilrys/funceble
# GitHub : https://github.com/funilrys/funceble


################################ Contributors ##################################
################################ Contributors ##################################
# - @mitchellkrogza, Mitchell Krog <mitchellkrog@gmail.com>
# - @mitchellkrogza, Mitchell Krog <mitchellkrog@gmail.com>
# - badreferslist: used along the construction of this script :)
# - badreferslist: used along the construction of this script :)
# @Source: https://git.io/vQPz8
# @Source: https://git.io/vQPz8
# - Idea of implementation of a timeout for whois
# - Idea of implementation of a timeout for whois
# @Source: https://git.io/vQPz0
# @Source: https://git.io/vQPz0
# - Idea of implementation of HTTP Code analyze
# - Idea of implementation of HTTP Code analyze
# @Source: https://git.io/v7Ci6
# @Source: https://git.io/v7Ci6
# - @PromoFaux, Adam Warner <adamw@rner.email> with Pi-Hole <https://pi-hole.net>
# - @PromoFaux, Adam Warner <adamw@rner.email> with Pi-Hole <https://pi-hole.net>
# - Their blocking list is just awesome to test this script :)
# - Their blocking list is just awesome to test this script :)
# - @WaLLy3K <github@firebog.net>
# - @WaLLy3K <github@firebog.net>
# - Idea of implementation of execution time
# - Idea of implementation of execution time
# @Source: https://git.io/vQPzg
# @Source: https://git.io/vQPzg
################################################################################
################################################################################




################################# Temporary ####################################&&
################################# Temporary ####################################&&
# Path to temporary file
# Path to temporary file
whoIs="/var/tmp/whois.$$"
whoIs="/var/tmp/whois.$$"
################################################################################
################################################################################
################################### Files ######################################
################################### Files ######################################
# IANA Root Zone Database file.
# IANA Root Zone Database file.
# The file is a dump of the extensions this script can accept.
# The file is a dump of the extensions this script can accept.
# For update use: `tool --iana`
# For update use: `tool --iana`
# Source: https://www.iana.org/domains/root/db
# Source: https://www.iana.org/domains/root/db
ianaDB="iana-domains-db"
ianaDB="iana-domains-db"
################################################################################
################################################################################
############################### Text Format ###################################
############################### Text Format ###################################
# Bold
# Bold
bold=$(tput bold)
bold=$(tput bold)


# Cyan Color
# Cyan Color
cyan=$(tput setaf 6)
cyan=$(tput setaf 6)


# Magenta Color
# Magenta Color
magenta=$(tput setaf 5)
magenta=$(tput setaf 5)


# Disable formating
# Disable formating
normal=$(tput sgr0)
normal=$(tput sgr0)


# Red Color
# Red Color
red=$(tput setaf 1)
red=$(tput setaf 1)


# White Color
# White Color
white=$(tput setaf 7)
white=$(tput setaf 7)


################################################################################
################################################################################
################################## Status ######################################
################################## Status ######################################
# Down domain status
# Down domain status
downStatus="INACTIVE"
downStatus="INACTIVE"


# Invalid domain status
# Invalid domain status
invalidStatus="INVALID"
invalidStatus="INVALID"


# Valid domain status
# Valid domain status
upStatus="ACTIVE"
upStatus="ACTIVE"
################################################################################
################################################################################
############################## Default Values ##################################
############################## Default Values ##################################
# Activation of the auto-continue mode
# Activation of the auto-continue mode
autoContinue=true
autoContinue=true


# Used to check if we already cleaned hosts file
# Used to check if we already cleaned hosts file
cleanedDone=false
cleanedDone=false


# Current Date
# Current Date
currentDate=$(date)
currentDate=$(date)


# IP for host file
# IP for host file
customIP='0.0.0.0'
customIP='0.0.0.0'


# Generate debug file under log
# Generate debug file under log
# DO NOT USE THIS IF YOU DON'T KNOW HOW TO DEBUG FROM OUTPUTTED FILE
# DO NOT USE THIS IF YOU DON'T KNOW HOW TO DEBUG FROM OUTPUTTED FILE
debugUnknown=false
debugUnknown=false


# File already treated
# File already treated
fileAlreadyTreated=false
fileAlreadyTreated=false


# Activate/Desactivate the generation of hosts file
# Activate/Desactivate the generation of hosts file
generateHosts=false
generateHosts=false


# Link to script
# Link to script
linkScript="https://github.com/funilrys/funceble"
linkScript="https://github.com/funilrys/funceble"


# If noFiles=true, We don't any results files ==> Not applied to hosts file
# If noFiles=true, We don't any results files ==> Not applied to hosts file
noFiles=false
noFiles=false


# Number of domain which returns inactive
# Number of domain which returns inactive
numberOfDown=0
numberOfDown=0


# Number of domain which returns invalid
# Number of domain which returns invalid
numberOfInvalid=0
numberOfInvalid=0


# Number of domain tested
# Number of domain tested
numberOfTested=0
numberOfTested=0


# Number of active
# Number of active
numberOfUp=0
numberOfUp=0


# Output less data
# Output less data
outputLess=false
outputLess=false


# Output logs
# Output logs
outputLogs=true
outputLogs=true


# Output unified file
# Output unified file
outputUnified=true
outputUnified=true


# If set to true, we don't print anything
# If set to true, we don't print anything
quiet=false
quiet=false


# Regex to match
# Regex to match
regexCurrentDir='%%currentDir%%'
regexCurrentDir='%%currentDir%%'


# IPv4 match
# IPv4 match
regexIPv4='(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
regexIPv4='(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'


# HTTP Status code timeout
# HTTP Status code timeout
secondsBeforeHTTPTimeout=5
secondsBeforeHTTPTimeout=5


# Default seconds before timeout
# Default seconds before timeout
secondsBeforeTimeout=30
secondsBeforeTimeout=30


# Show/hide execution time
# Show/hide execution time
showExecutionTime=false
showExecutionTime=false


# Show/hide percentage
# Show/hide percentage
showPercentage=true
showPercentage=true


# Activation/deactivation of travis mode
# Activation/deactivation of travis mode
travisMode=false
travisMode=false


# Minimum of minutes before we start commiting to upstream under travis
# Minimum of minutes before we start commiting to upstream under travis
travisAutoSaveMinutes=30
travisAutoSaveMinutes=30


# If set to false, we generate only one file with the results
# If set to false, we generate only one file with the results
splitFiles=false
splitFiles=false


# Version number
# Version number
versionNumber='dev-1.4.0+56'
versionNumber='dev-1.4.0+59'


# IANA whois server. The following is there to give use the whois
# IANA whois server. The following is there to give use the whois
# host we have to call to get a (valid) response.
# host we have to call to get a (valid) response.
# Note: Whois Server are different for each extension.
# Note: Whois Server are different for each extension.
whoisServer="whois.iana.org"
whoisServer="whois.iana.org"
################################################################################
################################################################################
################################## Outputs #####################################
################################## Outputs #####################################
# Defaut name for hosts file
# Defaut name for hosts file
hostsDefault='hosts'
hostsDefault='hosts'


# Defaut name for domain list
# Defaut name for domain list
domainsDefault='list'
domainsDefault='list'


# Output directory.
# Output directory.
# Auto updated with `tool -i`
# Auto updated with `tool -i`
# DO NOT FORGET '/' AT THE END
# DO NOT FORGET '/' AT THE END
outputDir='%%currentDir%%/output/'
outputDir='%%currentDir%%/output/'


# Autocontinue log file
# Autocontinue log file
continueLog=${outputDir}continue.txt
continueLog=${outputDir}continue.txt


# domains directory
# domains directory
domainsDir=${outputDir}domains/
domainsDir=${outputDir}domains/


# INACTIVE domains directory
# INACTIVE domains directory
downDomainsDir=${domainsDir}INACTIVE/
downDomainsDir=${domainsDir}INACTIVE/


# ACTIVE domains directory
# ACTIVE domains directory
upDomainsDir=${domainsDir}ACTIVE/
upDomainsDir=${domainsDir}ACTIVE/


# INVALID hosts directory
# INVALID hosts directory
invalidDomainsDir=${domainsDir}INVALID/
invalidDomainsDir=${domainsDir}INVALID/


# hosts directory
# hosts directory
hostsDir=${outputDir}hosts/
hostsDir=${outputDir}hosts/


# INACTIVE hosts directory
# INACTIVE hosts directory
downHostsDir=${hostsDir}INACTIVE/
downHostsDir=${hostsDir}INACTIVE/


# ACTIVE hosts directory
# ACTIVE hosts directory
upHostsDir=${hostsDir}ACTIVE/
upHostsDir=${hostsDir}ACTIVE/


# INVALID hosts directory
# INVALID hosts directory
invalidHostsDir=${hostsDir}INVALID/
invalidHostsDir=${hostsDir}INVALID/


# Output of log
# Output of log
logOutput=${outputDir}'logs/'
logOutput=${outputDir}'logs/'


# Whois output
# Whois output
whoisLogOutput=${logOutput}whois/
whoisLogOutput=${logOutput}whois/


# Date output
# Date output
dateLogOutput=${logOutput}dateFormat/
dateLogOutput=${logOutput}dateFormat/


# Percentages output
# Percentages output
percentageLogOutput=${logOutput}percentage/
percentageLogOutput=${logOutput}percentage/


# Output of execution Time log
# Output of execution Time log
executionLog=${logOutput}execution.log
executionLog=${logOutput}execution.log


# Ouput of no referer log
# Ouput of no referer log
noRefererLogOutput=${logOutput}noReferer/
noRefererLogOutput=${logOutput}noReferer/


# Output of inactive domains
# Output of inactive domains
outputDownDomain=${downDomainsDir}${domainsDefault}
outputDownDomain=${downDomainsDir}${domainsDefault}


# Output of active domains
# Output of active domains
outputUpDomain=${upDomainsDir}${domainsDefault}
outputUpDomain=${upDomainsDir}${domainsDefault}


# Output of invalid domains
# Output of invalid domains
outputInvalidDomain=${invalidDomainsDir}${domainsDefault}
outputInvalidDomain=${invalidDomainsDir}${domainsDefault}


# Output of inactive domain
# Output of inactive domain
outputDownHost=${downHostsDir}${hostsDefault}
outputDownHost=${downHostsDir}${hostsDefault}


# Output of active domain
# Output of active domain
outputUpHost=${upHostsDir}${hostsDefault}
outputUpHost=${upHostsDir}${hostsDefault}


# Output of invalid domain
# Output of invalid domain
outputInvalidHost=${invalidHostsDir}${hostsDefault}
outputInvalidHost=${invalidHostsDir}${hostsDefault}


# Output of unified results
# Output of unified results
outputUnifiedResult=${outputDir}result.txt
outputUnifiedResult=${outputDir}result.txt


# Output of valid results
# Output of valid results
outputUpResult=${outputDir}splited/active.txt
outputUpResult=${outputDir}splited/active.txt


# Output of invalid results
# Output of invalid results
outputInvalidResult=${outputDir}splited/invalid.txt
outputInvalidResult=${outputDir}splited/invalid.txt


# Output of error results
# Output of error results
outputDownResult=${outputDir}splited/inactive.txt
outputDownResult=${outputDir}splited/inactive.txt


# Output of persentage log
# Output of persentage log
outputPercentageLog=${percentageLogOutput}percentage.txt
outputPercentageLog=${percentageLogOutput}percentage.txt


# Output of HTTP codes
# Output of HTTP codes
outputHTTPCodes=${outputDir}HTTP_Analytic/
outputHTTPCodes=${outputDir}HTTP_Analytic/


# Output of active codes if different from "funceble" result
# Output of active codes if different from "funceble" result
outputHTTPActive=${outputHTTPCodes}ACTIVE/
outputHTTPActive=${outputHTTPCodes}ACTIVE/


# Lof of output active
# Lof of output active
logOutputHTTPActive=${outputHTTPActive}active.txt
logOutputHTTPActive=${outputHTTPActive}active.txt


# Ouput of potentially active codes
# Ouput of potentially active codes
outputHTTPPotentiallyActive=${outputHTTPCodes}POTENTIALLY_ACTIVE/
outputHTTPPotentiallyActive=${outputHTTPCodes}POTENTIALLY_ACTIVE/


# Log of output of potentially active codes
# Log of output of potentially active codes
logOutputHTTPPotentiallyActive=${outputHTTPPotentiallyActive}potentially_active.txt
logOutputHTTPPotentiallyActive=${outputHTTPPotentiallyActive}potentially_active.txt


# Output of inactive and potentially inactive codes
# Output of inactive and potentially inactive codes
outputHTTPInactiveOrPotentially=${outputHTTPCodes}POTENTIALLY_INACTIVE/
outputHTTPInactiveOrPotentially=${outputHTTPCodes}POTENTIALLY_INACTIVE/


# Log of output of inactive or potentially inactive codes
# Log of output of inactive or potentially inactive codes
logOutputHTTPInactiveOrPotentially=${outputHTTPInactiveOrPotentially}inactive_or_potentially.txt
logOutputHTTPInactiveOrPotentially=${outputHTTPInactiveOrPotentially}inactive_or_potentially.txt
################################################################################
################################################################################
############################# HTTP Code validation #############################
############################# HTTP Code validation #############################
# Active codes
# Active codes
activeCodes=('100' '101' '200' '201' '202' '203' '204' '205' '206')
activeCodes=('100' '101' '200' '201' '202' '203' '204' '205' '206')


# Potentially active codes
# Potentially active codes
potentiallyActiveCodes=('000' '300' '301' '302' '303' '304' '305' '307' '403' '405' '406' '407' '408' '411' '413' '417' '500' '501' '502' '503' '504' '505')
potentiallyActiveCodes=('000' '300' '301' '302' '303' '304' '305' '307' '403' '405' '406' '407' '408' '411' '413' '417' '500' '501' '502' '503' '504' '505')


# Inactive or pothentially inactive codes
# Inactive or pothentially inactive codes
inactiveOrPotentiallyCodes=('400' '403' '402' '404' '409' '410' '412' '414' '415' '416')
inactiveOrPotentiallyCodes=('400' '403' '402' '404' '409' '410' '412' '414' '415' '416')
################################################################################
################################################################################


# _______ _ _______ __________________ _______ _ _______
# _______ _ _______ __________________ _______ _ _______
# ( ____ \|\ /|( ( /|( ____ \\__ __/\__ __/( ___ )( ( /|( ____ \
# ( ____ \|\ /|( ( /|( ____ \\__ __/\__ __/( ___ )( ( /|( ____ \
# | ( \/| ) ( || \ ( || ( \/ ) ( ) ( | ( ) || \ ( || ( \/
# | ( \/| ) ( || \ ( || ( \/ ) ( ) ( | ( ) || \ ( || ( \/
# | (__ | | | || \ | || | | | | | | | | || \ | || (_____
# | (__ | | | || \ | || | | | | | | | | || \ | || (_____
# | __) | | | || (\ \) || | | | | | | | | || (\ \) |(_____ )
# | __) | | | || (\ \) || | | | | | | | | || (\ \) |(_____ )
# | ( | | | || | \ || | | | | | | | | || | \ | ) |
# | ( | | | || | \ || | | | | | | | | || | \ | ) |
# | ) | (___) || ) \ || (____/\ | | ___) (___| (___) || ) \ |/\____) |
# | ) | (___) || ) \ || (____/\ | | ___) (___| (___) || ) \ |/\____) |
# |/ (_______)|/ )_)(_______/ )_( \_______/(_______)|/ )_)\_______)
# |/ (_______)|/ )_)(_______/ )_( \_______/(_______)|/ )_)\_______)


############################### Before Header ##################################
############################### Before Header ##################################
# Used to print some infomations before the header dataoutputDownResult comes.
# Used to print some infomations before the header dataoutputDownResult comes.
#
#
# @CalledBy getReferer
# @CalledBy getReferer
################################################################################
################################################################################
beforeHeader(){
beforeHeader(){
# We get the file we're gonna print into
# We get the file we're gonna print into
# file <string>
# file <string>
local fileToCreate="${1}"
local fileToCreate="${1}"
if [[ ! -f ${fileToCreate} ]]
if [[ ! -f ${fileToCreate} ]]
then
then
# If does not exist we add informations about funceble and the Date
# If does not exist we add informations about funceble and the Date
# of the generation of the file.
# of the generation of the file.
printf "# File generated with %s\n" "${linkScript}" > ${fileToCreate}
printf "# File generated with %s\n" "${linkScript}" > ${fileToCreate}
printf "# Date of generation: %s\n" "${currentDate}" >> ${fileToCreate}
printf "# Date of generation: %s\n" "${currentDate}" >> ${fileToCreate}
printf "\n" >> ${fileToCreate}
printf "\n" >> ${fileToCreate}
fi
fi
}
}


############################### Print Header ###################################
############################### Print Header ###################################
# Used to print header
# Used to print header
# if quiet=false it's printing in file
# if quiet=false it's printing in file
#
#
# @CalledBy getReferer
# @CalledBy getReferer
################################################################################
################################################################################
printHeader()
printHeader()
{
{
# type <string>
# type <string>
local type=${1}
local type=${1}
if [[ ${type} == 'Invalid' ]]
if [[ ${type} == 'Invalid' ]]
then
then
# Generation of header for invalid.txt
# Generation of header for invalid.txt
printf "\n%-100s %-17s %-10s %-10s %-8s\n" "Domain" "Status" "Source" "HTTP Code" "Analyse Date"
printf "\n%-100s %-17s %-10s %-10s %-8s\n" "Domain" "Status" "Source" "HTTP Code" "Analyse Date"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- ---------- ----------------------------"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- ---------- ----------------------------"
elif [[ ${type} == 'Down' ]]
elif [[ ${type} == 'Down' ]]
then
then
# Generation of header for inactive.txt
# Generation of header for inactive.txt
printf "\n%-100s %-35s %-17s %10s %-10s %-20s\n" "Domain" "WHOIS Server" "Status" "Source" "HTTP Code" "Analyse Date"
printf "\n%-100s %-35s %-17s %10s %-10s %-20s\n" "Domain" "WHOIS Server" "Status" "Source" "HTTP Code" "Analyse Date"
echo "---------------------------------------------------------------------------------------------------- ----------------------------------- ----------- ---------- ---------- ----------------------------"
echo "---------------------------------------------------------------------------------------------------- ----------------------------------- ----------- ---------- ---------- ----------------------------"
elif [[ ${type} == 'Up' ]]
elif [[ ${type} == 'Up' ]]
then
then
# Generation of header for valid.txt
# Generation of header for valid.txt
printf "\n%-100s %-17s %-17s %-10s %-10s %-20s\n" "Domain" "Status" "Expiration Date" "Source" "HTTP Code" "Analyse Date"
printf "\n%-100s %-17s %-17s %-10s %-10s %-20s\n" "Domain" "Status" "Expiration Date" "Source" "HTTP Code" "Analyse Date"
echo "---------------------------------------------------------------------------------------------------- ----------- ----------------- ---------- ---------- -------------------------------"
echo "---------------------------------------------------------------------------------------------------- ----------- ----------------- ---------- ---------- -------------------------------"
elif [[ ${type} == 'Generic' ]]
elif [[ ${type} == 'Generic' ]]
then
then
# Generation of header (On screen)
# Generation of header (On screen)
printf "\n%-100s %-11s %-17s %-10s %-10s\n" "Domain" "Status" "Expiration Date" "Source" "HTTP Code"
printf "\n%-100s %-11s %-17s %-10s %-10s\n" "Domain" "Status" "Expiration Date" "Source" "HTTP Code"
echo "---------------------------------------------------------------------------------------------------- ----------- ----------------- ---------- ----------"
echo "---------------------------------------------------------------------------------------------------- ----------- ----------------- ---------- ----------"
elif [[ ${type} == 'Generic_File' ]]
elif [[ ${type} == 'Generic_File' ]]
then
then
# Generation of header (On file)
# Generation of header (On file)
printf "\n%-100s %-11s %-17s %-10s %-10s %-20s\n" "Domain" "Status" "Expiration Date" "Source" "HTTP Code" "Analyse Date"
printf "\n%-100s %-11s %-17s %-10s %-10s %-20s\n" "Domain" "Status" "Expiration Date" "Source" "HTTP Code" "Analyse Date"
echo "---------------------------------------------------------------------------------------------------- ----------- ----------------- ---------- ---------- -------------------------------"
echo "---------------------------------------------------------------------------------------------------- ----------- ----------------- ---------- ---------- -------------------------------"
elif [[ ${type} == 'Less' ]]
elif [[ ${type} == 'Less' ]]
then
then
# Generation of header (On screen)
# Generation of header (On screen)
printf "\n%-100s %-11s %-10s %-10s\n" "Domain" "Status" "Source" "HTTP Code"
printf "\n%-100s %-11s %-10s %-10s\n" "Domain" "Status" "Source" "HTTP Code"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- ----------"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- ----------"
elif [[ ${type} == 'Less_File' ]]
elif [[ ${type} == 'Less_File' ]]
then
then
# Generation of header (On file)
# Generation of header (On file)
printf "\n%-100s %-11s %-10s %-10s\n" "Domain" "Status" "Source" "HTTP Code"
printf "\n%-100s %-11s %-10s %-10s\n" "Domain" "Status" "Source" "HTTP Code"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- ----------"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- ----------"
elif [[ ${type} == 'Percentage' ]]
elif [[ ${type} == 'Percentage' ]]
then
then
# Generation of header
# Generation of header
printf "\n%-11s %-12s %-12s\n" "Status" "Percentage" "Numbers"
printf "\n%-11s %-12s %-12s\n" "Status" "Percentage" "Numbers"
echo "----------- ------------ -------------"
echo "----------- ------------ -------------"
elif [[ ${type} == 'HTTP' ]]
elif [[ ${type} == 'HTTP' ]]
then
then
# Generation of header
# Generation of header
printf "\n%-100s %-11s %-10s %-20s\n" "Domain" "Status" "HTTP Code" "Analyse Date"
printf "\n%-100s %-11s %-10s %-20s\n" "Domain" "Status" "HTTP Code" "Analyse Date"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- -------------------------------"
echo "---------------------------------------------------------------------------------------------------- ----------- ---------- -------------------------------"
fi
fi
}
}


################################# Prints #######################################
################################# Prints #######################################
# Come with printHeader(). In charge to print/input generated data.
# Come with printHeader(). In charge to print/input generated data.
#
#
# @CalledBy getReferer
# @CalledBy getReferer
################################################################################
################################################################################
prints()
prints()
{
{
# type <string>
# type <string>
local type=${1}
local type=${1}
# We use the current full date as Analyse Date
# We use the current full date as Analyse Date
local dateAn=$(date)
local dateAn=$(date)
if [[ ${type} == 'Invalid' ]]
if [[ ${type} == 'Invalid' ]]
then
then
# Print data for invalid.txt
# Print data for invalid.txt
printf "%-100s %-17s %-8s %-10s %-8s\n" "${2}" "${invalidStatus}" "${3}" "${httpCode}" "${dateAn}"
printf "%-100s %-17s %-8s %-10s %-8s\n" "${2}" "${invalidStatus}" "${3}" "${httpCode}" "${dateAn}"
elif [[ ${type} == 'Down' ]]
elif [[ ${type} == 'Down' ]]
then
then
# Print data for inactive.txt
# Print data for inactive.txt
printf "%-100s %-35s %-17s %8s %-10s %-20s\n" "${2}" "${3}" "${downStatus}" "${4}" "${httpCode}" "${dateAn}"
printf "%-100s %-35s %-17s %8s %-10s %-20s\n" "${2}" "${3}" "${downStatus}" "${4}" "${httpCode}" "${dateAn}"
elif [[ ${type} == 'Up' ]]
elif [[ ${type} == 'Up' ]]
then
then
# Print data for valid.txt
# Print data for valid.txt
printf "%-100s %-17s %-17s %-8s %-10s %-20s\n" "${2}" "${upStatus}" "${3}" "${4}" "${httpCode}" "${dateAn}"
printf "%-100s %-17s %-17s %-8s %-10s %-20s\n" "${2}" "${upStatus}" "${3}" "${4}" "${httpCode}" "${dateAn}"
elif [[ ${type} == 'Generic' ]]
elif [[ ${type} == 'Generic' ]]
then
then
# Print data
# Print data
printf "%-100s %-11s %-17s %-10s %-10s\n" "${2}" "${3}" "${4}" "${5}" "${httpCode}"
printf "%-100s %-11s %-17s %-10s %-10s\n" "${2}" "${3}" "${4}" "${5}" "${httpCode}"
elif [[ ${type} == 'Generic_File' ]]
elif [[ ${type} == 'Generic_File' ]]
then
then
# Print data
# Print data
printf "%-100s %-11s %-17s %-10s %-10s %-20s\n" "${2}" "${3}" "${4}" "${5}" "${httpCode}" "${dateAn}"
printf "%-100s %-11s %-17s %-10s %-10s %-20s\n" "${2}" "${3}" "${4}" "${5}" "${httpCode}" "${dateAn}"
elif [[ ${type} == 'FullHosts' ]]
elif [[ ${type} == 'FullHosts' ]]
then
then
# Print host file
# Print host file
printf "%s %s\n" "${customIP}" "${2}"
printf "%s %s\n" "${customIP}" "${2}"
elif [[ ${type} == 'Less' ]]
elif [[ ${type} == 'Less' ]]
then
then
# Print data
# Print data
printf "%-100s %-11s %-10s %-10s\n" "${2}" "${3}" "${4}" "${httpCode}"
printf "%-100s %-11s %-10s %-10s\n" "${2}" "${3}" "${4}" "${httpCode}"
elif [[ ${type} == 'Less_File' ]]
elif [[ ${type} == 'Less_File' ]]
then
then
# Print data
# Print data
printf "%-100s %-11s %-10s %-10s\n" "${2}" "${3}" "${4}" "${httpCode}"
printf "%-100s %-11s %-10s %-10s\n" "${2}" "${3}" "${4}" "${httpCode}"
elif [[ ${type} == 'Percentage' ]]
elif [[ ${type} == 'Percentage' ]]
then
then
# Please consider the following as a hack because I had some headache
# Please consider the following as a hack because I had some headache
# when trying to fix some sort of scope issue when calling
# when trying to fix some sort of scope issue when calling
# $(percentage 'result' '{active,inactive,invalid}')
# $(percentage 'result' '{active,inactive,invalid}')
# This should may be fixed in the future once I figure out how to fix my
# This should may be fixed in the future once I figure out how to fix my
# HEADACHE !!!
# HEADACHE !!!
# We set the regex we're going to use in order to catch the numbers we need
# We set the regex we're going to use in order to catch the numbers we need
local regexNumberToMatch="${escapedFile}\s(.*)\s([[:digit:]]+)\s([[:digit:]]+)\s+([[:digit:]]+)\s+([[:digit:]]+)"
local regexNumberToMatch="${escapedFile}\s(.*)\s([[:digit:]]+)\s([[:digit:]]+)\s+([[:digit:]]+)\s+([[:digit:]]+)"
# If the content match the previously assigned regex variable
# If the content match the previously assigned regex variable
if [[ -f ${continueLog} && "$(cat ${continueLog})" =~ ${regexNumberToMatch} ]]
if [[ -f ${continueLog} && "$(cat ${continueLog})" =~ ${regexNumberToMatch} ]]
then
then
# We get the last number of tested
# We get the last number of tested
local numberOfTested=${BASH_REMATCH[2]}
local numberOfTested=${BASH_REMATCH[2]}
# We get the last number of UP
# We get the last number of UP
local numberOfUp=${BASH_REMATCH[3]}
local numberOfUp=${BASH_REMATCH[3]}
# We get the last number of down
# We get the last number of down
local numberOfDown=${BASH_REMATCH[4]}
local numberOfDown=${BASH_REMATCH[4]}
# We get the last number of invalid
# We get the last number of invalid
local numberOfInvalid=${BASH_REMATCH[5]}
local numberOfInvalid=${BASH_REMATCH[5]}
fi
fi
# We calculate the percentage
# We calculate the percentage
((percentageOfActive=${numberOfUp}*100/${numberOfTested}))
((percentageOfActive=${numberOfUp}*100/${numberOfTested}))
((percentageOfInactive=${numberOfDown}*100/${numberOfTested}))
((percentageOfInactive=${numberOfDown}*100/${numberOfTested}))
((percentageOfInvalid=${numberOfInvalid}*100/${numberOfTested}))
((percentageOfInvalid=${numberOfInvalid}*100/${numberOfTested}))
printf "%-11s %-12s %-12s\n" "ACTIVE" "${percentageOfActive}%" "${numberOfUp}"
printf "%-11s %-12s %-12s\n" "ACTIVE" "${percentageOfActive}%" "${numberOfUp}"
printf "%-11s %-12s %-12s\n" "INACTIVE" "${percentageOfInactive}%" "${numberOfDown}"
printf "%-11s %-12s %-12s\n" "INACTIVE" "${percentageOfInactive}%" "${numberOfDown}"
printf "%-11s %-12s %-12s\n" "INVALID" "${percentageOfInvalid}%" "${numberOfInvalid}"
printf "%-11s %-12s %-12s\n" "INVALID" "${percentageOfInvalid}%" "${numberOfInvalid}"
elif [[ ${type} == 'HTTP' ]]
elif [[ ${type} == 'HTTP' ]]
then
then
printf "%-100s %-11s %-10s %-20s\n" "${domain}" "${2}" "${3}" "${dateAn}"
printf "%-100s %-11s %-10s %-20s\n" "${domain}" "${2}" "${3}" "${dateAn}"
fi
fi
}
}




################################### Timeout ####################################
################################### Timeout ####################################
# In charge to initiate a timeout for commands
# In charge to initiate a timeout for commands
#
#
# @CalledBy timeout, getExpirationDate
# @CalledBy timeout, getExpirationDate
################################################################################
################################################################################
timeout (){
timeout (){
# type <int|string>
# type <int|string>
time=${1}
time=${1}
# Create the temporary file
# Create the temporary file
touch ${whoIs}
touch ${whoIs}
# start the command in a subshell in order to avoid problem with pipes
# start the command in a subshell in order to avoid problem with pipes
command="/bin/bash -c \"${2}\""
command="/bin/bash -c \"${2}\""
expect -c "set echo \"-noecho\"; set timeout ${time}; spawn -noecho ${command}; expect timeout { exit 1 } eof { exit 0 }"
expect -c "set echo \"-noecho\"; set timeout ${time}; spawn -noecho ${command}; expect timeout { exit 1 } eof { exit 0 }"
}
}


############################# Generate Hosts File ##############################
############################# Generate Hosts File ##############################
# In charge to print data into hosts file
# In charge to print data into hosts file
#
#
# @CalledBy generateStatusFile
# @CalledBy generateStatusFile
################################################################################
################################################################################
generateHostsFile()
generateHostsFile()
{
{
# type <string>
# type <string>
local type="${1}"
local type="${1}"
# We preassign the variable
# We preassign the variable
local domainOutput=''
local domainOutput=''
if [[ ${generateHosts} == true ]]
if [[ ${generateHosts} == true ]]
then
then
# We clean the files in case we need to start from begining
# We clean the files in case we need to start from begining
if [[ ${fileAlreadyTreated} == false || ${startFromBegining} == true ]]
if [[ ${fileAlreadyTreated} == false || ${startFromBegining} == true ]]
then
then
if [[ ${cleanedDone} == false ]]
if [[ ${cleanedDone} == false ]]
then
then
if [[ -f ${outputUpHost} ]]
if [[ -f ${outputUpHost} ]]
then
then
rm -f ${outputUpHost}
rm -f ${outputUpHost}
fi
fi
if [[ -f ${outputDownHost} ]]
if [[ -f ${outputDownHost} ]]
then
then
rm -f ${outputDownHost}
rm -f ${outputDownHost}
fi
fi
if [[ -f ${outputInvalidHost} ]]
if [[ -f ${outputInvalidHost} ]]
then
then
rm -f ${outputInvalidHost}
rm -f ${outputInvalidHost}
fi
fi
if [[ -f ${outputUnifiedResult} ]]
if [[ -f ${outputUnifiedResult} ]]
then
then
# We delete the result.txt file here because generateHostsFile() is
# We delete the result.txt file here because generateHostsFile() is
# always called before generateUnifiedFile()
# always called before generateUnifiedFile()
rm -f ${outputUnifiedResult}
rm -f ${outputUnifiedResult}
fi
fi
if [[ -f ${outputUpResult} ]]
if [[ -f ${outputUpResult} ]]
then
then
rm -f ${outputUpResult}
rm -f ${outputUpResult}
fi
fi
if [[ -f ${outputDownResult} ]]
if [[ -f ${outputDownResult} ]]
then
then
rm -f ${outputDownResult}
rm -f ${outputDownResult}
fi
fi
if [[ -f ${outputInvalidResult} ]]
if [[ -f ${outputInvalidResult} ]]
then
then
rm -f ${outputInvalidResult}
rm -f ${outputInvalidResult}
fi
fi
cleanedDone=true
cleanedDone=true
fi
fi
fi
fi
case ${type} in
case ${type} in
'up'|'Up'|'UP'|'active'|'Active'|'ACTIVE'|'valid'|'Valid'|'VALID')
'up'|'Up'|'UP'|'active'|'Active'|'ACTIVE'|'valid'|'Valid'|'VALID')
local outputDestination="${outputUpHost}"
local outputDestination="${outputUpHost}"
local domainOutput="${outputUpDomain}"
local domainOutput="${outputUpDomain}"
;;
;;
'down'|'Down'|'DOWN'|'inactive'|'Inactive'|'INACTIVE'|'error'|'Error'|'ERROR')
'down'|'Down'|'DOWN'|'inactive'|'Inactive'|'INACTIVE'|'error'|'Error'|'ERROR')
local outputDestination="${outputDownHost}"
local outputDestination="${outputDownHost}"
local domainOutput="${outputDownDomain}"
local domainOutput="${outputDownDomain}"
;;
;;
'invalid'|'Invalid'|'INVALID')
'invalid'|'Invalid'|'INVALID')
local outputDestination="${outputInvalidHost}"
local outputDestination="${outputInvalidHost}"
local domainOutput="${outputInvalidDomain}"
local domainOutput="${outputInvalidDomain}"
;;
;;
'potentially_up'|'potentially_active')
'potentially_up'|'potentially_active')
local outputDestination="${outputHTTPPotentiallyActive}${hostsDefault}"
local outputDestination="${outputHTTPPotentiallyActive}${hostsDefault}"
;;
;;
'potentially_down'|'potentially_inacative')
'potentially_down'|'potentially_inacative')
local outputDestination="${outputHTTPInactiveOrPotentially}${hostsDefault}"
local outputDestination="${outputHTTPInactiveOrPotentially}${hostsDefault}"
;;
;;
'http_active'|'HTTP_ACTIVE'|'HTTP_active'|'HTTP_Active')
'http_active'|'HTTP_ACTIVE'|'HTTP_active'|'HTTP_Active')
local outputDestination="${outputHTTPActive}${hostsDefault}"
local outputDestination="${outputHTTPActive}${hostsDefault}"
;;
;;
esac
esac
# We print / create the inactive file
# We print / create the inactive file
beforeHeader "${outputDestination}"
beforeHeader "${outputDestination}"
prints 'FullHosts' "${domain}" >> ${outputDestination}
prints 'FullHosts' "${domain}" >> ${outputDestination}
if [[ ${domainOutput} != '' ]]
if [[ ${domainOutput} != '' ]]
then
then
beforeHeader "${domainOutput}"
beforeHeader "${domainOutput}"
printf "%s\n" "${domain}" >> ${domainOutput}
printf "%s\n" "${domain}" >> ${domainOutput}
fi
fi
fi
fi
}
}


########################### Generate Unified File ##############################
########################### Generate Unified File ##############################
# In charge to print data into result.txt
# In charge to print data into result.txt
#
#
# @CalledBy generateInvalidFile,generateErrorFile,generateValidFile
# @CalledBy generateInvalidFile,generateErrorFile,generateValidFile
################################################################################
################################################################################
generateUnifiedFile()
generateUnifiedFile()
{
{
# type <string>
# type <string>
local type=${1}
local type=${1}
# status <string>
# status <string>
local status=${2}
local status=${2}
# expdate <string>
# expdate <string>
local expdate=${3}
local expdate=${3}
if [[ ${outputUnified} == true ]]
if [[ ${outputUnified} == true ]]
then
then
if [[ -f ${outputUnifiedResult} ]]
if [[ -f ${outputUnifiedResult} ]]
then
then
if [[ ${outputLess} == true ]]
if [[ ${outputLess} == true ]]
then
then
# We save the domain and his data to the unified file
# We save the domain and his data to the unified file
prints "Less_File" "${domain}" "${status}" "${type}" >> ${outputUnifiedResult}
prints "Less_File" "${domain}" "${status}" "${type}" >> ${outputUnifiedResult}
else
else
# We save the domain and his data to the unified file
# We save the domain and his data to the unified file
prints "Generic_File" "${domain}" "${status}" "${expdate}" "${type}" >> ${outputUnifiedResult}
prints "Generic_File" "${domain}" "${status}" "${expdate}" "${type}" >> ${outputUnifiedResult}
fi
fi
else
else
if [[ ${outputLess} == true ]]
if [[ ${outputLess} == true ]]
then
then
# We create header into and in between, create the file
# We create header into and in between, create the file
beforeHeader ${outputUnifiedResult}
beforeHeader ${outputUnifiedResult}
printHeader "Less_File" >> ${outputUnifiedResult}
printHeader "Less_File" >> ${outputUnifiedResult}
# We save the domain and his data to the unified file
# We save the domain and his data to the unified file
prints "Less_File" "${domain}" "${status}" "${type}" >> ${outputUnifiedResult}
prints "Less_File" "${domain}" "${status}" "${type}" >> ${outputUnifiedResult}
else
else
# We create header into and in between, create the file
# We create header into and in between, create the file
beforeHeader ${outputUnifiedResult}
beforeHeader ${outputUnifiedResult}
printHeader "Generic_File" >> ${outputUnifiedResult}
printHeader "Generic_File" >> ${outputUnifiedResult}
# We save the domain and his data to the unified file
# We save the domain and his data to the unified file
prints "Generic_File" "${domain}" "${status}" "${expdate}" "${type}" >> ${outputUnifiedResult}
prints "Generic_File" "${domain}" "${status}" "${expdate}" "${type}" >> ${outputUnifiedResult}
fi
fi
fi
fi
fi
fi
}
}


############################## Generate Status File ############################
############################## Generate Status File ############################
# In charge to print print files according to their status
# In charge to print print files according to their status
#
#
# @CalledBy errorHandle
# @CalledBy errorHandle
################################################################################
################################################################################
generateStatusFile(){
generateStatusFile(){
# We get the type of the request
# We get the type of the request
# type <string>
# type <string>
local type="${1}"
local type="${1}"
# Where does the source come from
# Where does the source come from
# source <string>
# source <string>
local source="${2}"
local source="${2}"
# The expiration date
# The expiration date
# expiredDate <string>
# expiredDate <string>
local expiredDate="${3}"
local expiredDate="${3}"
# We use this variable in order to know if we changes the status with th results
# We use this variable in order to know if we changes the status with th results
# of httpCode()
# of httpCode()
local notActive=true
local notActive=true
case ${type} in
case ${type} in
'up'|'Up'|'UP'|'active'|'Active'|'ACTIVE'|'valid'|'Valid'|'VALID')
'up'|'Up'|'UP'|'active'|'Active'|'ACTIVE'|'valid'|'Valid'|'VALID')
# If empty, we change the expiration date to `Unknown`
# If empty, we change the expiration date to `Unknown`
if [[ ${expiredDate} == '' ]]
if [[ ${expiredDate} == '' ]]
then
then
expiredDate='Unknown'
expiredDate='Unknown'
fi
fi
# We do some analytic
# We do some analytic
if [[ ${inactiveOrPotentiallyCodes[*]} =~ ${httpCode} ]]
if [[ ${inactiveOrPotentiallyCodes[*]} =~ ${httpCode} ]]
then
then
generateAnalyticFile 'Down' "${upStatus}"
generateAnalyticFile 'Down' "${upStatus}"
fi
fi
# We assign the official status name
# We assign the official status name
local readStatus=${upStatus}
local readStatus=${upStatus}
# We assign the location of the splited file
# We assign the location of the splited file
local putDataIntoMe=${outputUpResult}
local putDataIntoMe=${outputUpResult}
# we generate the host file
# we generate the host file
generateHostsFile 'active'
generateHostsFile 'active'
# We increment the percentage
# We increment the percentage
percentage 'counter' 'active'
percentage 'counter' 'active'
;;
;;
'down'|'Down'|'DOWN'|'inactive'|'Inactive'|'INACTIVE'|'error'|'Error'|'ERROR')
'down'|'Down'|'DOWN'|'inactive'|'Inactive'|'INACTIVE'|'error'|'Error'|'ERROR')
# We assign "Not Found" to prevent empty column in splited file
# We assign "Not Found" to prevent empty column in splited file
local giveMeMyRefererStatus='Not Found'
local giveMeMyRefererStatus='Not Found'
# We assign the official status name
# We assign the official status name
local readStatus=${downStatus}
local readStatus=${downStatus}
# We assign the location of the splited file
# We assign the location of the splited file
local putDataIntoMe=${outputDownResult}
local putDataIntoMe=${outputDownResult}
# We change the expiration date to `Unknown`
# We change the expiration date to `Unknown`
local expiredDate='Unknown'
local expiredDate='Unknown'
# We do some analytic
# We do some analytic
if [[ ${activeCodes[*]} =~ ${httpCode} ]]
if [[ ${activeCodes[*]} =~ ${httpCode} ]]
then
then
generateAnalyticFile 'Up' "${status}"
generateAnalyticFile 'Up' "${status}"
# We generate the host file
# We generate the host file
generateHostsFile 'active'
generateHostsFile 'active'