]> git.ipfire.org Git - people/ms/network.git/blame - src/functions/functions.util
security-policies: Delete cached content when policy is deleted
[people/ms/network.git] / src / functions / functions.util
CommitLineData
1848564d
MT
1#!/bin/bash
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
5# Copyright (C) 2010 Michael Tremer & Christian Schmidt #
6# #
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. #
11# #
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. #
16# #
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/>. #
19# #
20###############################################################################
21
97cb552e 22# A simple print statement
1c6a4e30 23print() {
acc9efd5
MT
24 local fmt=${1}; shift
25
40e3553f 26 printf -- "${fmt}\n" "$@"
97cb552e
MT
27}
28
67baa452
MT
29print_indent() {
30 local i=${1}
31 shift
32
33 while (( i-- )); do
34 printf "\t"
35 done
36
37 print "%s" "$@"
38}
39
cb965348
MT
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
1c6a4e30 43args() {
cb965348
MT
44 echo "$@" | xargs printf "%s\n"
45}
46
1c6a4e30 47unquote() {
04854c77
MT
48 local var="$@"
49
50 if [ "${var:0:1}" = "\"" ]; then
51 var=${var:1}
52 fi
53
54 local last=$(( ${#var} - 1 ))
55 if [ ${last} -ge 0 ] && [ "${var:${last}:1}" = "\"" ]; then
56 var=${var:0:${last}}
57 fi
58
59 print "${var}"
60}
61
1c6a4e30 62quote() {
04854c77
MT
63 print "\"%s\"" "$@"
64}
65
1c6a4e30 66strip() {
fe52c5e0
MT
67 local value="$@"
68
69 # remove leading whitespace characters
70 value="${value#"${value%%[![:space:]]*}"}"
71
72 # remove trailing whitespace characters
73 value="${value%"${value##*[![:space:]]}"}"
74
75 print "${value}"
76}
77
1848564d 78# Print a pretty error message
1c6a4e30 79error() {
fcbf6823 80 echo -e " ${CLR_RED_B}ERROR${CLR_RESET} : $@" >&2
1848564d
MT
81}
82
1c6a4e30 83error_log() {
1b7a1578
MT
84 log ERROR "$@"
85}
86
1848564d 87# Print a pretty warn message
1c6a4e30 88warning() {
fcbf6823 89 echo -e " ${CLR_YELLOW_B}WARNING${CLR_RESET}: $@" >&2
1848564d
MT
90}
91
1c6a4e30 92warning_log() {
1b7a1578
MT
93 log WARNING "$@"
94}
95
1848564d 96# Speedup function to avoid a call of the basename binary
1c6a4e30 97basename() {
1848564d
MT
98 echo "${1##*/}"
99}
100
1c6a4e30 101format() {
e5651e17
MT
102 local key=${1}
103 assert isset key
104
105 local format=${2}
106 assert isset format
107
108 shift 2
109
110 printf -v "${key}" "${format}" "$@"
111}
112
d13929d4
MT
113format_time() {
114 local s=${1}
115 local ret m
116
117 local units="s m h"
118
119 local unit
120 for unit in ${units}; do
121 m=$(( ${s} % 60 ))
122 s=$(( ${s} / 60 ))
123
124 if [ ${m} -gt 0 ]; then
125 ret="${m}${unit} ${ret}"
126 fi
127 done
128
129 # Remove whitespace
130 echo ${ret}
131}
132
b383499d
MT
133parse_time() {
134 local ret=0
135
136 local arg
137 for arg in $@; do
138 local unit
139
140 case "${arg}" in
141 *h|*m|*s)
142 # Store unit
143 unit="${arg: -1}"
144
145 # Remove unit
146 arg="${arg:0:-1}"
147 ;;
148 esac
149
150 if ! isinteger arg; then
151 return ${EXIT_ERROR}
152 fi
153
154 # Convert hours and minutes into seconds
155 case "${unit}" in
156 h)
157 arg=$(( ${arg} * 3600 ))
158 ;;
159 m)
160 arg=$(( ${arg} * 60 ))
161 ;;
162 esac
163
164 # Add up everything
165 ret=$(( ${ret} + ${arg} ))
166 done
167
168 print "${ret}"
169}
170
1c6a4e30 171assign() {
b79ad79b
MT
172 local key=${1}
173 assert isset key
174 shift
175
e5651e17 176 format "${key}" "%s" "$@"
b79ad79b
MT
177}
178
1c6a4e30 179fread() {
b79ad79b
MT
180 local file=${1}
181 assert isset file
182
183 [ -r "${file}" ] || return ${EXIT_ERROR}
184
185 print "$(<${file})"
186}
187
1c6a4e30 188fwrite() {
b79ad79b
MT
189 local file=${1}
190 assert isset file
191 shift
192
e1947a76 193 if [ -e "${file}" ] && [ ! -w "${file}" ]; then
8d4e0d52
MT
194 log ERROR "${file}: No such file"
195 return ${EXIT_ERROR}
196 fi
197
198 print "%s" "$@" >> ${file} 2>/dev/null
b79ad79b
MT
199}
200
e1947a76
MT
201file_exists() {
202 local file=${1}
203
204 [ -e "${file}" ] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
205}
206
207file_is_newer_than() {
208 local file1="${1}"
209 local file2="${2}"
210
211 local age1=$(file_get_age "${file1}")
212 local age2=$(file_get_age "${file2}")
213
214 if [ ${age1} -gt ${age2} ]; then
215 return ${EXIT_TRUE}
216 else
217 return ${EXIT_FALSE}
218 fi
219}
220
221file_get_age() {
222 local file="${1}"
223
224 if [ -e "${file}" ]; then
225 stat --format="%Y" "${file}"
226 return $?
227 fi
228
229 return ${EXIT_ERROR}
230}
231
c041b631
MT
232make_parent_dir() {
233 local path="${1}"
234
235 local dirname="$(dirname "${path}")"
236 mkdir -p "${dirname}"
237}
238
1c6a4e30 239enabled() {
1848564d
MT
240 local param=${1}
241
e726ef8d 242 list_match "${!param}" yes on true 1
1848564d
MT
243}
244
1c6a4e30 245mac_generate() {
fb1416c6
MT
246 local b="$(random 12)"
247
248 # Remove multicast bit
249 # and set address is software assigned
250 local first_byte=$(( 0x${b:0:2} & 0xfe ))
251 first_byte=$(( ${first_byte} | 0x02 ))
1848564d
MT
252
253 local output
fb1416c6 254 printf -v output "%02x" "${first_byte}"
790b7ec9 255
fb1416c6 256 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
1848564d
MT
257
258 # Check if output is valid
fb1416c6 259 assert mac_is_valid "${output}"
1848564d 260
790b7ec9 261 echo "${output}"
1848564d
MT
262}
263
1c6a4e30 264mac_format() {
18b43372 265 local mac=${1}
48bc31eb 266 assert isset mac
18b43372 267
48bc31eb
MT
268 # Remove all colons and make the rest lowercase.
269 mac=${mac//:/}
270 mac=${mac,,}
18b43372 271
48bc31eb 272 local output
18b43372
MT
273 if [ "${#mac}" = "12" ]; then
274 # Add colons (:) to mac address
275 output=${mac:0:2}
276 local i
277 for i in 2 4 6 8 10; do
278 output="${output}:${mac:${i}:2}"
279 done
48bc31eb
MT
280 else
281 output=${mac}
18b43372
MT
282 fi
283
284 assert mac_is_valid ${output}
285
48bc31eb 286 print "${output}"
18b43372
MT
287}
288
1c6a4e30 289mac_is_valid() {
1848564d
MT
290 local mac=${1}
291
292 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
293}
294
1c6a4e30 295uuid() {
de543653 296 echo $(</proc/sys/kernel/random/uuid)
1848564d
MT
297}
298
a24cff8f
JS
299abs() {
300 local val=${1}
301
302 if [ ${val} -lt 0 ]; then
303 (( val *= -1 ))
304 fi
305
306 echo ${val}
307}
308
fb1416c6
MT
309rand() {
310 local uuid="$(uuid)"
311 echo "${uuid//-/}"
312}
313
314random() {
315 local length="${1:-8}"
316
317 local random
318 while [ ${#random} -lt ${length} ]; do
319 random="${random}$(rand)"
320 done
321
322 echo "${random:0:${length}}"
323}
324
1c6a4e30 325isset() {
1848564d
MT
326 local var=${1}
327
328 [ -n "${!var}" ]
329}
330
1c6a4e30 331isoneof() {
1848564d
MT
332 local var=${!1}
333 shift
334
e726ef8d 335 list_match "${var}" "$@"
1848564d
MT
336}
337
1c6a4e30 338isbool() {
1848564d
MT
339 local var=${1}
340
ec6afbdd 341 isoneof ${var} 0 1 no yes on off true false
1848564d
MT
342}
343
1c6a4e30 344isinteger() {
1848564d
MT
345 local var=${!1}
346
347 [[ ${var} =~ ^[0-9]+$ ]]
348}
349
1c6a4e30 350ismac() {
1848564d
MT
351 local mac=${!1}
352
353 mac_is_valid ${mac}
354}
355
1c6a4e30 356isipaddress() {
fef4edaf
MT
357 local addr=${!1}
358
359 ip_is_valid ${addr}
360}
361
48a64768
JS
362mtu_is_valid() {
363 local proto=${1}
364 local mtu=${2}
365
366 case ${proto} in
367 ipv4)
368 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
369 ;;
370 ipv6)
371 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
372 ;;
373 *)
374 error "${proto} is not a valid proto"
375 return ${EXIT_ERROR}
376 ;;
377 esac
378}
379
1c6a4e30 380backtrace() {
711ffac1
MT
381 local start=1
382
383 echo # Empty line
384 error_log "Backtrace (most recent call in first line):"
385
04608623 386 local i source
711ffac1
MT
387 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
388 [ -z "${FUNCNAME[${i}]}" ] && continue
6396ccab
MT
389
390 # Print called binary with arguments.
391 if [ "${FUNCNAME[${i}]}" == "main" ]; then
392 local args="$(list_reverse ${BASH_ARGV[*]})"
393 printf -v source "%20s" "$0"
394 error_log " ${source} ${args}"
395 continue
396 fi
711ffac1 397
04608623
MT
398 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
399 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
711ffac1
MT
400 done
401}
402
1c6a4e30 403assert() {
1848564d
MT
404 local assertion="$@"
405
406 if ! ${assertion}; then
4c670d7c 407 error_log "Assertion '${assertion}' failed."
711ffac1 408 backtrace
cfbe0802 409 exit ${EXIT_ERROR_ASSERT}
1848564d
MT
410 fi
411
412 return ${EXIT_OK}
413}
cad8bd85 414
b0b2f995
MT
415# This function checks, if the given argument is an assert error
416# exit code. If this is the case, the script will halt immediately.
1c6a4e30 417assert_check_retval() {
b0b2f995
MT
418 local ret=${1}
419
420 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
421 exit ${EXIT_ERROR_ASSERT}
422 fi
423
424 return ${ret}
425}
426
2bb20bbd
SS
427# This function executes the given command and inverses the return code
428not() {
429 local command="$@"
430
431 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
432}
433
1c6a4e30 434exec_cmd() {
711ffac1
MT
435 local cmd=$@
436
437 log DEBUG "Running command: ${cmd}"
438
b816e04b 439 DEBUG=${DEBUG} \
8c63fa13
MT
440 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
441 LOG_FACILITY="${LOG_FACILITY}" \
b816e04b 442 ${SHELL} ${cmd}
711ffac1
MT
443 local ret=$?
444
445 #log DEBUG "Returned with code '${ret}'"
446
447 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
448 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
449 exit ${EXIT_ERROR_ASSERT}
450 fi
451
452 return ${ret}
453}
454
1c6a4e30 455cmd() {
b816e04b
MT
456 local cmd=$@
457
458 log DEBUG "Running command: ${cmd}"
459
11285da0
MT
460 if ! ${cmd}; then
461 local ret=$?
b816e04b 462
11285da0
MT
463 log DEBUG "Returned with code '${ret}'"
464 return ${ret}
465 fi
b816e04b 466
11285da0 467 return ${EXIT_OK}
b816e04b
MT
468}
469
1c6a4e30 470cmd_quiet() {
98146c00 471 cmd $@ &>/dev/null
3efecbb3
MT
472}
473
1c6a4e30 474cmd_exec() {
f80ce052
MT
475 local cmd=$@
476
477 log DEBUG "Exec'ing command: ${cmd}"
478
479 exec ${cmd}
480
481 log ERROR "Could not exec-ute: ${cmd}"
482 exit ${EXIT_ERROR}
483}
484
1c6a4e30 485cmd_not_implemented() {
2181765d
MT
486 assert false "not implemented"
487}
488
de3cecef
MT
489# Runs a command in a clean environment so that no confidential information
490# is leaked to any untrusted commands.
491cmd_clean_environment() {
492 local cmd=$@
493
494 log DEBUG "Running command in a clean environment: ${cmd}"
495 env -i -- ${cmd}
496 local ret=${?}
497
498 log DEBUG "Returned with code '${ret}'"
499 return ${ret}
500}
501
f5ee091e
MT
502# Executes the given command in background
503cmd_background() {
504 cmd_quiet $@ &
505}
506
507# Prints the PID of the process that was started last
508cmd_background_get_pid() {
509 print "${!}"
510}
511
512cmd_background_result() {
513 local pids=$@
514
515 wait ${pids}
516}
517
b8026986 518# Increase security of the read command
1c6a4e30 519read() {
b8026986
MT
520 builtin read -r $@
521}
522
1c6a4e30 523seq() {
3efecbb3
MT
524 if [ $# -eq 2 ]; then
525 eval echo {${1}..${2}}
526 elif [ $# -eq 3 ]; then
527 eval echo {${1}..${3}..${2}}
528 fi
529}
530
de72bd91
MT
531range() {
532 eval echo {0..$(( ${1} - 1 ))}
533}
534
535count() {
536 local i=0
537
538 while read; do
539 ((i++))
540 done
541
542 echo ${i}
543}
544
1c6a4e30 545which() {
76e6cd51
MT
546 type -P $@
547}
548
fe52c5e0 549# Prints the number of seconds since epoch.
1c6a4e30 550timestamp() {
fe52c5e0
MT
551 date -u "+%s"
552}
553
1c6a4e30 554beautify_time() {
d82cf370
MT
555 local value=${1}
556
557 local unit
558 local limit
559 for unit in s m h d w; do
560 case "${unit}" in
561 s|m|h)
562 limit=60
563 ;;
564 d)
565 limit=24
566 ;;
567 w)
568 limit=7
569 ;;
570 esac
571
572 [ ${value} -lt ${limit} ] && break
573
574 value=$(( ${value} / ${limit} ))
575 done
576
577 echo "${value}${unit}"
578}
711ffac1 579
1c6a4e30 580beautify_bytes() {
711ffac1
MT
581 local value=${1}
582
583 local unit
584 local limit=1024
585 for unit in B k M G T; do
586 [ ${value} -lt ${limit} ] && break
587 value=$(( ${value} / ${limit} ))
588 done
589
590 echo "${value}${unit}"
591}
943e3f7e 592
1c6a4e30 593module_load() {
943e3f7e
MT
594 local module=${1}
595
596 if ! grep -q "^${module}" /proc/modules; then
597 log DEBUG "Loading module '${module}'."
598 modprobe ${module}
599 fi
600}
6b3f9c85 601
1c6a4e30 602binary_exists() {
6b3f9c85
MT
603 local binary=${1}
604
605 if [ -n "$(type -p ${binary})" ]; then
606 return ${EXIT_OK}
607 fi
608
609 return ${EXIT_ERROR}
610}
d76f5107 611
1c6a4e30 612function_exists() {
1e6f187e
MT
613 local function="${1}"
614
615 if [ "$(type -t "${function}")" = "function" ]; then
616 return ${EXIT_TRUE}
617 fi
618
619 return ${EXIT_FALSE}
620}
621
1c6a4e30 622process_kill() {
d76f5107
MT
623 local process=${1}
624
625 if ! isinteger process; then
626 process=$(pidof ${process})
627 fi
628
629 local pid
630 local sig
631 for pid in ${process}; do
632 for sig in 15 9; do
633 [ -d "/proc/${pid}" ] || break
634
635 kill -${sig} ${pid}
636 sleep 1
637 done
638 done
639}
feb76eaf 640
1c6a4e30 641dec() {
feb76eaf
MT
642 local hex=${1}
643
644 if [ "${hex:0:2}" != "0x" ]; then
645 hex="0x${hex}"
646 fi
647
648 printf "%d\n" "${hex}"
649}
3a7fef62 650
1c6a4e30 651chr() {
5cf0edf9
MT
652 local char="${1}"
653
654 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
655
656 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
657}
658
1c6a4e30 659ord() {
5cf0edf9
MT
660 LC_CTYPE="C" printf "%d\n" "'${1}"
661}
662
1c6a4e30 663hex() {
5cf0edf9
MT
664 printf "%X\n" "${1}"
665}
666
1c6a4e30 667network_is_running() {
3a7fef62
MT
668 # Check, if the network service is running.
669 service_is_active network
670}
f80ce052 671
1c6a4e30 672contains_spaces() {
f80ce052
MT
673 local var="$@"
674
675 # Eliminate spaces.
676 local var2=${var// /}
677
678 if [ ${#var} -ne ${#var2} ]; then
679 return ${EXIT_TRUE}
680 fi
681
682 return ${EXIT_FALSE}
0d645497
MT
683}
684
685string_match() {
686 local match=${1}
687 local string=${2}
688
689 [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
f80ce052 690}
5cf0edf9 691
1c6a4e30 692string_split() {
5cf0edf9
MT
693 local string="$@"
694
695 local pos=0
696 while [ ${pos} -lt ${#string} ]; do
697 print "${string:${pos}:1}"
698 pos=$(( ${pos} + 1 ))
699 done
700
701 return ${EXIT_OK}
702}
703
1c6a4e30 704string_reverse() {
5cf0edf9
MT
705 local string="$@"
706
707 local output
708 local pos=0
709 while [ ${pos} -lt ${#string} ]; do
710 output="${string:${pos}:1}${output}"
711 pos=$(( ${pos} + 1 ))
712 done
713
714 print "${output}"
715 return ${EXIT_OK}
716}
717
1c6a4e30 718dec2bin() {
5cf0edf9
MT
719 local number="${1}"
720
721 local output
722
723 local i div
724 for i in 7 6 5 4 3 2 1; do
725 div=$(( 2 ** ${i} ))
726
727 if [ $(( ${number} / ${div} )) -eq 1 ]; then
728 output="${output}1"
729 else
730 output="${output}0"
731 fi
732 number="$(( ${number} % ${div} ))"
733 done
734
735 if [ $(( ${number} % 2 )) -eq 1 ]; then
736 output="${output}1"
737 else
738 output="${output}0"
739 fi
740
741 print "${output}"
742}
743
1c6a4e30 744bin2dec() {
5cf0edf9
MT
745 local string="${1}"
746 local number=0
747
748 local pos=0 char
749 while [ ${pos} -lt ${#string} ]; do
750 char="${string:${pos}:1}"
751 pos=$(( ${pos} + 1 ))
752
753 number=$(( ${number} << 1 ))
754
755 case "${char}" in
756 0) ;;
757 1)
758 number=$(( ${number} + 1 ))
759 ;;
760 *)
761 assert false "Invalid character: ${char}"
762 ;;
763 esac
764 done
765
766 print "${number}"
767 return ${EXIT_OK}
768}
769
1c6a4e30 770char2bin() {
5cf0edf9
MT
771 local dec="$(ord "${1}")"
772
773 dec2bin "${dec}"
774}
775
1c6a4e30 776bin2char() {
5cf0edf9
MT
777 local dec="$(bin2dec "$@")"
778
779 chr "${dec}"
780}
781
1c6a4e30 782bin2hex() {
5cf0edf9
MT
783 local dec="$(bin2dec "$@")"
784
785 dec2hex "${dec}"
786}
787
1c6a4e30 788hex2bin() {
5cf0edf9
MT
789 local dec="$(hex2dec "$@")"
790
791 dec2bin "${dec}"
792}
793
1c6a4e30 794hex2dec() {
5cf0edf9
MT
795 local hex="${1}"
796
797 # Prepend 0x if necessary.
798 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
799
800 printf "%d\n" "${hex}"
801}
802
1c6a4e30 803dec2hex() {
5cf0edf9
MT
804 printf "%02x\n" "${1}"
805}
a95d16fc 806
10b53c87 807# This function just copy config files
a95d16fc 808copy() {
a95d16fc
JS
809 assert [ $# -eq 2 ]
810
811 local src=${1}
812 local dst=${2}
813
287c2e60
MT
814 # Check if we can read from the source
815 if [ ! -r "${src}" ]; then
816 log ERROR "Cannot read ${src}"
817 return ${EXIT_ERROR}
818 fi
819
a95d16fc 820 # Check if ${dst} is a directory
1fade616 821 if [ -d "${dst}" ]; then
9c802e1d 822 log ERROR "${dst} is a directory"
a95d16fc
JS
823 return ${EXIT_ERROR}
824 fi
825
826 if ! fread "${src}" > "${dst}"; then
827 log ERROR "Could not copy data from ${src} to ${dst}"
828 return ${EXIT_ERROR}
829 fi
830}