]>
git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
39ad8613b6e4419c5ef97e86c900e63ac9d75383
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2010 Michael Tremer & Christian Schmidt #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
22 # A simple print statement
26 printf -- "${fmt}\n" "$@"
40 # The args() function takes a number of arguments like
41 # var1="abc d" var2="abc" var3="abcd e"
42 # and splits them into several arguments, devided by newline
44 echo "$@" |
xargs printf "%s\n"
50 if [ "${var:0:1}" = "\"" ]; then
54 local last
=$
(( ${#var} - 1 ))
55 if [ ${last} -ge 0 ] && [ "${var:${last}:1}" = "\"" ]; then
69 # remove leading whitespace characters
70 value="${value#"${value%%[![:space:]]*}"}"
72 # remove trailing whitespace characters
73 value="${value%"${value##*[![:space:]]}"}"
78 # Print a pretty error message
80 echo -e " ${CLR_RED_B}ERROR
${CLR_RESET} : $@
" >&2
87 # Print a pretty warn message
89 echo -e " ${CLR_YELLOW_B}WARNING
${CLR_RESET}: $@
" >&2
96 # Speedup function to avoid a call of the basename binary
110 printf -v "${key}" "${format}" "$@
"
120 for unit in ${units}; do
124 if [ ${m} -gt 0 ]; then
125 ret="${m}${unit} ${ret}"
150 if ! isinteger arg; then
154 # Convert hours and minutes into seconds
157 arg=$(( ${arg} * 3600 ))
160 arg=$(( ${arg} * 60 ))
165 ret=$(( ${ret} + ${arg} ))
176 format "${key}" "%s
" "$@
"
183 [ -r "${file}" ] || return ${EXIT_ERROR}
193 if ! print "%s
" "$@
" > ${file} 2>/dev/null; then
194 error "Could not
write to
file: ${file}"
206 if [ -e "${file}" ] && [ ! -w "${file}" ]; then
207 log ERROR "${file}: No such
file"
211 print "%s
" "$@
" >> ${file} 2>/dev/null
217 unlink "${file}" 2>/dev/null
223 [ -e "${file}" ] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
226 file_is_newer_than
() {
230 local age1
=$
(file_get_age
"${file1}")
231 local age2
=$
(file_get_age
"${file2}")
233 if [ ${age1} -gt ${age2} ]; then
243 if [ -e "${file}" ]; then
244 stat
--format="%Y" "${file}"
256 assert file_exists
"${file}"
260 log
"${level}" "${line}"
267 # Exit silently when directory already exists
268 if [ -d "${path}" ]; then
272 if ! mkdir
-p "${path}"; then
273 log ERROR
"Could not create directory ${path}"
277 log DEBUG
"Created directory ${path}"
281 make_parent_directory
() {
284 make_directory
"$(dirname "${path}")"
290 list_match
"${!param}" yes on true
1
296 list_match
"${!param}" no off false
0
300 local b
="$(random 12)"
302 # Remove multicast bit
303 # and set address is software assigned
304 local first_byte
=$
(( 0x
${b:0:2} & 0xfe ))
305 first_byte
=$
(( ${first_byte} |
0x02 ))
308 printf -v output
"%02x" "${first_byte}"
310 output
="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
312 # Check if output is valid
313 assert mac_is_valid
"${output}"
322 # Remove all colons and make the rest lowercase.
327 if [ "${#mac}" = "12" ]; then
328 # Add colons (:) to mac address
331 for i
in 2 4 6 8 10; do
332 output
="${output}:${mac:${i}:2}"
338 assert mac_is_valid
${output}
346 [[ ${mac} =~ ^
([0-9a-f]{2}\
:){5}[0-9a-f]{2}$
]]
349 # Converts the given string to lowercase and returns true if it is a valid FQDN
353 if grep -qP "^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$" <<< "${fqdn,,}"; then
361 echo $
(</proc
/sys
/kernel
/random
/uuid
)
367 if [ ${val} -lt 0 ]; then
380 local length
="${1:-8}"
383 while [ ${#random} -lt ${length} ]; do
384 random
="${random}$(rand)"
387 echo "${random:0:${length}}"
400 list_match
"${var}" "$@"
406 isoneof
${var} 0 1 no
yes on off true false
412 [[ ${var} =~ ^
[0-9]+$
]]
433 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
436 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
439 error
"${proto} is not a valid proto"
449 error_log
"Backtrace (most recent call in first line):"
452 for i
in $
(seq ${start} ${#BASH_SOURCE[*]}); do
453 [ -z "${FUNCNAME[${i}]}" ] && continue
455 # Print called binary with arguments.
456 if [ "${FUNCNAME[${i}]}" == "main" ]; then
457 local args
="$(list_reverse ${BASH_ARGV[*]})"
458 printf -v source "%20s" "$0"
459 error_log
" ${source} ${args}"
463 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
464 error_log
" $(printf "%20s
" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
471 if ! ${assertion}; then
474 # End the program here
475 abort "Assertion failed: ${assertion}"
481 # Ends the program immediately without cleaning up
490 exit ${EXIT_ERROR_ASSERT}
493 # This function checks, if the given argument is an assert error
494 # exit code. If this is the case, the script will halt immediately.
495 assert_check_retval() {
498 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
499 exit ${EXIT_ERROR_ASSERT}
505 # This function executes the given command and inverses the return code
509 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
515 log DEBUG "Running command: ${cmd}"
518 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
519 LOG_FACILITY="${LOG_FACILITY}" \
523 #log DEBUG "Returned with code '${ret}'"
525 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
526 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
527 exit ${EXIT_ERROR_ASSERT}
536 log DEBUG "Running command: ${cmd}"
550 log DEBUG "Returned with code '${ret}'"
563 log DEBUG "Exec'ing
command: ${cmd}"
567 log ERROR "Could not exec-ute
: ${cmd}"
571 cmd_not_implemented() {
572 assert false "not implemented
"
575 # Executes the given command in background
580 # Prints the PID of the process that was started last
581 cmd_background_get_pid() {
585 cmd_background_result() {
591 # Increase security of the read command
597 if [ $# -eq 2 ]; then
598 eval echo {${1}..${2}}
599 elif [ $# -eq 3 ]; then
600 eval echo {${1}..${3}..${2}}
605 eval echo {0..$(( ${1} - 1 ))}
622 # Prints the number of seconds since epoch.
632 for unit in s m h d w; do
645 [ ${value} -lt ${limit} ] && break
647 value=$(( ${value} / ${limit} ))
650 echo "${value}${unit}"
658 for unit in B k M G T; do
659 [ ${value} -lt ${limit} ] && break
660 value=$(( ${value} / ${limit} ))
663 echo "${value}${unit}"
669 # Do nothing if the module is already loaded
670 if [ -d "/sys
/module
/${module//-/_}" ]; then
674 log DEBUG "Loading kernel module
${module}"
681 if [ -n "$
(type -p ${binary})" ]; then
689 local function="${1}"
691 if [ "$
(type -t "${function}")" = "function" ]; then
701 if ! isinteger process; then
702 process=$(pidof ${process})
707 for pid in ${process}; do
709 [ -d "/proc
/${pid}" ] || break
720 if [ "${hex:0:2}" != "0x
" ]; then
724 printf "%d
\n" "${hex}"
730 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
732 printf "\\$
(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
736 LC_CTYPE="C
" printf "%d
\n" "'${1}"
743 network_is_running() {
744 # Check, if the network service is running.
745 service_is_active network
752 local var2=${var// /}
754 if [ ${#var} -ne ${#var2} ]; then
761 contains_non_ascii_characters() {
764 # Strip away all ASCII characters
765 local non_ascii="${value//[[:ascii:]]/}"
767 if isset non_ascii; then
778 [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
785 while [ ${pos} -lt ${#string} ]; do
786 print "${string:${pos}:1}"
787 pos=$(( ${pos} + 1 ))
798 while [ ${pos} -lt ${#string} ]; do
799 output="${string:${pos}:1}${output}"
800 pos=$(( ${pos} + 1 ))
813 for i in 7 6 5 4 3 2 1; do
816 if [ $(( ${number} / ${div} )) -eq 1 ]; then
821 number="$(( ${number} % ${div} ))"
824 if [ $(( ${number} % 2 )) -eq 1 ]; then
838 while [ ${pos} -lt ${#string} ]; do
839 char="${string:${pos}:1}"
840 pos=$(( ${pos} + 1 ))
842 number=$(( ${number} << 1 ))
847 number=$(( ${number} + 1 ))
850 assert false "Invalid character: ${char}"
860 local dec="$(ord "${1}")"
866 local dec="$(bin2dec "$@")"
872 local dec="$(bin2dec "$@")"
878 local dec="$(hex2dec "$@")"
886 # Prepend 0x if necessary.
887 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
889 printf "%d\n" "${hex}"
893 printf "%02x\n" "${1}"
896 # This function just copy config files
903 # Check if we can read from the source
904 if [ ! -r "${src}" ]; then
905 log ERROR "Cannot read ${src}"
909 # Check if ${dst} is a directory
910 if [ -d "${dst}" ]; then
911 log ERROR "${dst} is a directory"
915 # Create destination directory if it doesn't exist
, yet
916 if ! make_parent_directory
"${dst}"; then
920 if ! fread
"${src}" > "${dst}"; then
921 log ERROR
"Could not copy data from ${src} to ${dst}"
929 tr -sc [:alnum
:] "-" < <(printf "%s" "${string,,}")
932 get_driver_from_path
() {
935 if file_exists
"${path}"; then
937 local driver
="$(readlink "${path}")"