]> git.ipfire.org Git - people/ms/network.git/blobdiff - src/functions/functions.util
wireless-ap: Check that secret has the correct length and no invalid characters
[people/ms/network.git] / src / functions / functions.util
index d26f519f4a43e0b1d348c9b395437d8554a8f891..7379a9887de812acf0eb812ef2cb2b0b7d0091e4 100644 (file)
@@ -26,6 +26,17 @@ print() {
        printf -- "${fmt}\n" "$@"
 }
 
+print_indent() {
+       local i=${1}
+       shift
+
+       while (( i-- )); do
+               printf "\t"
+       done
+
+       print "%s" "$@"
+}
+
 # The args() function takes a number of arguments like
 #   var1="abc d" var2="abc" var3="abcd e"
 # and splits them into several arguments, devided by newline
@@ -82,20 +93,6 @@ warning_log() {
        log WARNING "$@"
 }
 
-# The next three functions are kept for backwards
-# compatibility. The need to be dropped at some time.
-listsort() {
-       list_sort $@
-}
-
-listmatch() {
-       list_match $@
-}
-
-listlength() {
-       list_length $@
-}
-
 # Speedup function to avoid a call of the basename binary
 basename() {
        echo "${1##*/}"
@@ -113,6 +110,64 @@ format() {
        printf -v "${key}" "${format}" "$@"
 }
 
+format_time() {
+       local s=${1}
+       local ret m
+
+       local units="s m h"
+
+       local unit
+       for unit in ${units}; do
+               m=$(( ${s} % 60 ))
+               s=$(( ${s} / 60 ))
+
+               if [ ${m} -gt 0 ]; then
+                       ret="${m}${unit} ${ret}"
+               fi
+       done
+
+       # Remove whitespace
+       echo ${ret}
+}
+
+parse_time() {
+       local ret=0
+
+       local arg
+       for arg in "$@"; do
+               local unit
+
+               case "${arg}" in
+                       *h|*m|*s)
+                               # Store unit
+                               unit="${arg: -1}"
+
+                               # Remove unit
+                               arg="${arg:0:-1}"
+                               ;;
+               esac
+
+               if ! isinteger arg; then
+                       return ${EXIT_ERROR}
+               fi
+
+               # Convert hours and minutes into seconds
+               case "${unit}" in
+                       h)
+                               arg=$(( ${arg} * 3600 ))
+                               ;;
+                       m)
+                               arg=$(( ${arg} * 60 ))
+                               ;;
+               esac
+
+               # Add up everything
+               ret=$(( ${ret} + ${arg} ))
+       done
+
+       print "${ret}"
+}
+
 assign() {
        local key=${1}
        assert isset key
@@ -135,7 +190,20 @@ fwrite() {
        assert isset file
        shift
 
-       if [ ! -w "${file}" ]; then
+       if ! print "%s" "$@" > ${file} 2>/dev/null; then
+               error "Could not write to file: ${file}"
+               return ${EXIT_ERROR}
+       fi
+
+       return ${EXIT_OK}
+}
+
+fappend() {
+       local file=${1}
+       assert isset file
+       shift
+
+       if [ -e "${file}" ] && [ ! -w "${file}" ]; then
                log ERROR "${file}: No such file"
                return ${EXIT_ERROR}
        fi
@@ -143,11 +211,77 @@ fwrite() {
        print "%s" "$@" >> ${file} 2>/dev/null
 }
 
-make_parent_dir() {
+file_delete() {
+       local file=${1}
+
+       unlink "${file}" 2>/dev/null
+}
+
+file_exists() {
+       local file=${1}
+
+       [ -e "${file}" ] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
+}
+
+file_is_newer_than() {
+       local file1="${1}"
+       local file2="${2}"
+
+       local age1=$(file_get_age "${file1}")
+       local age2=$(file_get_age "${file2}")
+
+       if [ ${age1} -gt ${age2} ]; then
+               return ${EXIT_TRUE}
+       else
+               return ${EXIT_FALSE}
+       fi
+}
+
+file_get_age() {
+       local file="${1}"
+
+       if [ -e "${file}" ]; then
+               stat --format="%Y" "${file}"
+               return $?
+       fi
+
+       return ${EXIT_ERROR}
+}
+
+file_to_log() {
+       local level="${1}"
+       assert isset level
+
+       local file="${2}"
+       assert file_exists "${file}"
+
+       local line
+       while read line; do
+               log "${level}" "${line}"
+       done < "${file}"
+}
+
+make_directory() {
+       local path="${1}"
+
+       # Exit silently when directory already exists
+       if [ -d "${path}" ]; then
+               return ${EXIT_OK}
+       fi
+
+       if ! mkdir -p "${path}"; then
+               log ERROR "Could not create directory ${path}"
+               return ${EXIT_ERROR}
+       fi
+
+       log DEBUG "Created directory ${path}"
+       return ${EXIT_OK}
+}
+
+make_parent_directory() {
        local path="${1}"
 
-       local dirname="$(dirname "${path}")"
-       mkdir -p "${dirname}"
+       make_directory "$(dirname "${path}")"
 }
 
 enabled() {
@@ -156,37 +290,27 @@ enabled() {
        list_match "${!param}" yes on true 1
 }
 
-mac_generate() {
-       # Get a bunch of random hex digits
-       # and remove all dashes from the input.
-       local random=$(</proc/sys/kernel/random/uuid)
-       random=${random//-/}
-       assert isset random
+disabled() {
+       local param="${1}"
 
-       local output
+       list_match "${!param}" no off false 0
+}
 
-       local i o
-       for i in $(seq 0 5); do
-               o="0x${random:0:2}"
-               random="${random:2:${#random}}"
+mac_generate() {
+       local b="$(random 12)"
 
-               case "${i}" in
-                       0)
-                               # Remove multicast bit
-                               # and set address is software assigned
-                               o=$(( ${o} & 0xfe ))
-                               o=$(( ${o} | 0x02 ))
+       # Remove multicast bit
+       # and set address is software assigned
+       local first_byte=$(( 0x${b:0:2} & 0xfe ))
+       first_byte=$(( ${first_byte} | 0x02 ))
 
-                               printf -v output "%02x" "${o}"
-                               ;;
-                       *)
-                               printf -v output "%s:%02x" "${output}" "${o}"
-                               ;;
-               esac
-       done
+       local output
+       printf -v output "%02x" "${first_byte}"
+
+       output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
 
        # Check if output is valid
-       assert mac_is_valid ${output}
+       assert mac_is_valid "${output}"
 
        echo "${output}"
 }
@@ -222,10 +346,47 @@ mac_is_valid() {
        [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
 }
 
+# Converts the given string to lowercase and returns true if it is a valid FQDN
+fqdn_is_valid() {
+       local fqdn="${1}"
+
+       if grep -qP "^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$" <<< "${fqdn,,}"; then
+               return ${EXIT_TRUE}
+       fi
+
+       return ${EXIT_FALSE}
+}
+
 uuid() {
        echo $(</proc/sys/kernel/random/uuid)
 }
 
+abs() {
+       local val=${1}
+
+       if [ ${val} -lt 0 ]; then
+               (( val *= -1 ))
+       fi
+
+       echo ${val}
+}
+
+rand() {
+       local uuid="$(uuid)"
+       echo "${uuid//-/}"
+}
+
+random() {
+       local length="${1:-8}"
+
+       local random
+       while [ ${#random} -lt ${length} ]; do
+               random="${random}$(rand)"
+       done
+
+       echo "${random:0:${length}}"
+}
+
 isset() {
        local var=${1}
 
@@ -242,7 +403,7 @@ isoneof() {
 isbool() {
        local var=${1}
 
-       isoneof ${var} 0 1 no yes on off
+       isoneof ${var} 0 1 no yes on off true false
 }
 
 isinteger() {
@@ -263,6 +424,24 @@ isipaddress() {
        ip_is_valid ${addr}
 }
 
+mtu_is_valid() {
+       local proto=${1}
+       local mtu=${2}
+
+       case ${proto} in
+               ethernet|ipv4)
+                       [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
+                       ;;
+               ipv6)
+                       [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
+                       ;;
+               *)
+                       error "${proto} is not a valid proto"
+                       return ${EXIT_ERROR}
+                       ;;
+       esac
+}
+
 backtrace() {
        local start=1
 
@@ -310,6 +489,13 @@ assert_check_retval() {
        return ${ret}
 }
 
+# This function executes the given command and inverses the return code
+not() {
+       local command="$@"
+
+       ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
+}
+
 exec_cmd() {
        local cmd=$@
 
@@ -336,24 +522,34 @@ cmd() {
 
        log DEBUG "Running command: ${cmd}"
 
-       ${cmd}
+       env -i -- \
+               HOME="${HOME}" \
+               PATH="${PATH}" \
+               TERM="${TERM}" \
+               ${cmd}
        local ret=$?
 
-       log DEBUG "Returned with code '${ret}'"
-
-       return ${ret}
+       case "${ret}" in
+               ${EXIT_OK})
+                       return ${EXIT_OK}
+                       ;;
+               *)
+                       log DEBUG "Returned with code '${ret}'"
+                       return ${ret}
+                       ;;
+       esac
 }
 
 cmd_quiet() {
-       cmd $@ &>/dev/null
+       cmd "$@" &>/dev/null
 }
 
 cmd_exec() {
-       local cmd=$@
+       local cmd=( "$@" )
 
        log DEBUG "Exec'ing command: ${cmd}"
 
-       exec ${cmd}
+       exec "${cmd[@]}"
 
        log ERROR "Could not exec-ute: ${cmd}"
        exit ${EXIT_ERROR}
@@ -363,9 +559,25 @@ cmd_not_implemented() {
        assert false "not implemented"
 }
 
+# Executes the given command in background
+cmd_background() {
+       cmd_quiet "$@" &
+}
+
+# Prints the PID of the process that was started last
+cmd_background_get_pid() {
+       print "${!}"
+}
+
+cmd_background_result() {
+       local pids=$@
+
+       wait ${pids}
+}
+
 # Increase security of the read command
 read() {
-       builtin read -r $@
+       builtin read -r "$@"
 }
 
 seq() {
@@ -376,8 +588,22 @@ seq() {
        fi
 }
 
+range() {
+       eval echo {0..$(( ${1} - 1 ))}
+}
+
+count() {
+       local i=0
+
+       while read; do
+               ((i++))
+       done
+
+       echo ${i}
+}
+
 which() {
-       type -P $@
+       type -P "$@"
 }
 
 # Prints the number of seconds since epoch.
@@ -427,10 +653,13 @@ beautify_bytes() {
 module_load() {
        local module=${1}
 
-       if ! grep -q "^${module}" /proc/modules; then
-               log DEBUG "Loading module '${module}'."
-               modprobe ${module}
+       # Do nothing if the module is already loaded
+       if [ -d "/sys/module/${module//-/_}" ]; then
+               return ${EXIT_OK}
        fi
+
+       log DEBUG "Loading kernel module ${module}"
+       modprobe "${module}"
 }
 
 binary_exists() {
@@ -516,6 +745,26 @@ contains_spaces() {
        return ${EXIT_FALSE}
 }
 
+contains_non_ascii_characters() {
+       local value="$@"
+
+       # Strip away all ASCII characters
+       local non_ascii="${value//[[:ascii:]]/}"
+
+       if isset non_ascii; then
+               return ${EXIT_TRUE}
+       fi
+
+       return ${EXIT_FALSE}
+}
+
+string_match() {
+       local match=${1}
+       local string=${2}
+
+       [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
+}
+
 string_split() {
        local string="$@"
 
@@ -630,3 +879,54 @@ hex2dec() {
 dec2hex() {
        printf "%02x\n" "${1}"
 }
+
+# This function just copy config files
+copy() {
+       assert [ $# -eq 2 ]
+
+       local src=${1}
+       local dst=${2}
+
+       # Check if we can read from the source
+       if [ ! -r "${src}" ]; then
+               log ERROR "Cannot read ${src}"
+               return ${EXIT_ERROR}
+       fi
+
+       # Check if ${dst} is a directory
+       if [ -d "${dst}" ]; then
+               log ERROR "${dst} is a directory"
+               return ${EXIT_ERROR}
+       fi
+
+       # Create destination directory if it doesn't exist, yet
+       if ! make_parent_directory "${dst}"; then
+               return ${EXIT_ERROR}
+       fi
+
+       if ! fread "${src}" > "${dst}"; then
+               log ERROR "Could not copy data from ${src} to ${dst}"
+               return ${EXIT_ERROR}
+       fi
+}
+
+normalize() {
+       local string="$@"
+
+       tr -sc [:alnum:] "-" < <(printf "%s" "${string,,}")
+}
+
+get_driver_from_path() {
+       local path="${1}"
+
+       if file_exists "${path}"; then
+               # Resolve symlink
+               local driver="$(readlink "${path}")"
+
+               # Print module name
+               basename "${driver}"
+               return ${EXIT_OK}
+       fi
+
+       return ${EXIT_ERROR}
+}