]> git.ipfire.org Git - people/stevee/network.git/blame - src/functions/functions.util
ipsec: Only allow strict use of security policies
[people/stevee/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
8d4e0d52
MT
193 if [ ! -w "${file}" ]; then
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
c041b631
MT
201make_parent_dir() {
202 local path="${1}"
203
204 local dirname="$(dirname "${path}")"
205 mkdir -p "${dirname}"
206}
207
1c6a4e30 208enabled() {
1848564d
MT
209 local param=${1}
210
e726ef8d 211 list_match "${!param}" yes on true 1
1848564d
MT
212}
213
1c6a4e30 214mac_generate() {
fb1416c6
MT
215 local b="$(random 12)"
216
217 # Remove multicast bit
218 # and set address is software assigned
219 local first_byte=$(( 0x${b:0:2} & 0xfe ))
220 first_byte=$(( ${first_byte} | 0x02 ))
1848564d
MT
221
222 local output
fb1416c6 223 printf -v output "%02x" "${first_byte}"
790b7ec9 224
fb1416c6 225 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
1848564d
MT
226
227 # Check if output is valid
fb1416c6 228 assert mac_is_valid "${output}"
1848564d 229
790b7ec9 230 echo "${output}"
1848564d
MT
231}
232
1c6a4e30 233mac_format() {
18b43372 234 local mac=${1}
48bc31eb 235 assert isset mac
18b43372 236
48bc31eb
MT
237 # Remove all colons and make the rest lowercase.
238 mac=${mac//:/}
239 mac=${mac,,}
18b43372 240
48bc31eb 241 local output
18b43372
MT
242 if [ "${#mac}" = "12" ]; then
243 # Add colons (:) to mac address
244 output=${mac:0:2}
245 local i
246 for i in 2 4 6 8 10; do
247 output="${output}:${mac:${i}:2}"
248 done
48bc31eb
MT
249 else
250 output=${mac}
18b43372
MT
251 fi
252
253 assert mac_is_valid ${output}
254
48bc31eb 255 print "${output}"
18b43372
MT
256}
257
1c6a4e30 258mac_is_valid() {
1848564d
MT
259 local mac=${1}
260
261 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
262}
263
1c6a4e30 264uuid() {
de543653 265 echo $(</proc/sys/kernel/random/uuid)
1848564d
MT
266}
267
a24cff8f
JS
268abs() {
269 local val=${1}
270
271 if [ ${val} -lt 0 ]; then
272 (( val *= -1 ))
273 fi
274
275 echo ${val}
276}
277
fb1416c6
MT
278rand() {
279 local uuid="$(uuid)"
280 echo "${uuid//-/}"
281}
282
283random() {
284 local length="${1:-8}"
285
286 local random
287 while [ ${#random} -lt ${length} ]; do
288 random="${random}$(rand)"
289 done
290
291 echo "${random:0:${length}}"
292}
293
1c6a4e30 294isset() {
1848564d
MT
295 local var=${1}
296
297 [ -n "${!var}" ]
298}
299
1c6a4e30 300isoneof() {
1848564d
MT
301 local var=${!1}
302 shift
303
e726ef8d 304 list_match "${var}" "$@"
1848564d
MT
305}
306
1c6a4e30 307isbool() {
1848564d
MT
308 local var=${1}
309
ec6afbdd 310 isoneof ${var} 0 1 no yes on off true false
1848564d
MT
311}
312
1c6a4e30 313isinteger() {
1848564d
MT
314 local var=${!1}
315
316 [[ ${var} =~ ^[0-9]+$ ]]
317}
318
1c6a4e30 319ismac() {
1848564d
MT
320 local mac=${!1}
321
322 mac_is_valid ${mac}
323}
324
1c6a4e30 325isipaddress() {
fef4edaf
MT
326 local addr=${!1}
327
328 ip_is_valid ${addr}
329}
330
48a64768
JS
331mtu_is_valid() {
332 local proto=${1}
333 local mtu=${2}
334
335 case ${proto} in
336 ipv4)
337 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
338 ;;
339 ipv6)
340 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
341 ;;
342 *)
343 error "${proto} is not a valid proto"
344 return ${EXIT_ERROR}
345 ;;
346 esac
347}
348
1c6a4e30 349backtrace() {
711ffac1
MT
350 local start=1
351
352 echo # Empty line
353 error_log "Backtrace (most recent call in first line):"
354
04608623 355 local i source
711ffac1
MT
356 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
357 [ -z "${FUNCNAME[${i}]}" ] && continue
6396ccab
MT
358
359 # Print called binary with arguments.
360 if [ "${FUNCNAME[${i}]}" == "main" ]; then
361 local args="$(list_reverse ${BASH_ARGV[*]})"
362 printf -v source "%20s" "$0"
363 error_log " ${source} ${args}"
364 continue
365 fi
711ffac1 366
04608623
MT
367 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
368 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
711ffac1
MT
369 done
370}
371
1c6a4e30 372assert() {
1848564d
MT
373 local assertion="$@"
374
375 if ! ${assertion}; then
4c670d7c 376 error_log "Assertion '${assertion}' failed."
711ffac1 377 backtrace
cfbe0802 378 exit ${EXIT_ERROR_ASSERT}
1848564d
MT
379 fi
380
381 return ${EXIT_OK}
382}
cad8bd85 383
b0b2f995
MT
384# This function checks, if the given argument is an assert error
385# exit code. If this is the case, the script will halt immediately.
1c6a4e30 386assert_check_retval() {
b0b2f995
MT
387 local ret=${1}
388
389 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
390 exit ${EXIT_ERROR_ASSERT}
391 fi
392
393 return ${ret}
394}
395
2bb20bbd
SS
396# This function executes the given command and inverses the return code
397not() {
398 local command="$@"
399
400 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
401}
402
1c6a4e30 403exec_cmd() {
711ffac1
MT
404 local cmd=$@
405
406 log DEBUG "Running command: ${cmd}"
407
b816e04b 408 DEBUG=${DEBUG} \
8c63fa13
MT
409 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
410 LOG_FACILITY="${LOG_FACILITY}" \
b816e04b 411 ${SHELL} ${cmd}
711ffac1
MT
412 local ret=$?
413
414 #log DEBUG "Returned with code '${ret}'"
415
416 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
417 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
418 exit ${EXIT_ERROR_ASSERT}
419 fi
420
421 return ${ret}
422}
423
1c6a4e30 424cmd() {
b816e04b
MT
425 local cmd=$@
426
427 log DEBUG "Running command: ${cmd}"
428
11285da0
MT
429 if ! ${cmd}; then
430 local ret=$?
b816e04b 431
11285da0
MT
432 log DEBUG "Returned with code '${ret}'"
433 return ${ret}
434 fi
b816e04b 435
11285da0 436 return ${EXIT_OK}
b816e04b
MT
437}
438
1c6a4e30 439cmd_quiet() {
98146c00 440 cmd $@ &>/dev/null
3efecbb3
MT
441}
442
1c6a4e30 443cmd_exec() {
f80ce052
MT
444 local cmd=$@
445
446 log DEBUG "Exec'ing command: ${cmd}"
447
448 exec ${cmd}
449
450 log ERROR "Could not exec-ute: ${cmd}"
451 exit ${EXIT_ERROR}
452}
453
1c6a4e30 454cmd_not_implemented() {
2181765d
MT
455 assert false "not implemented"
456}
457
de3cecef
MT
458# Runs a command in a clean environment so that no confidential information
459# is leaked to any untrusted commands.
460cmd_clean_environment() {
461 local cmd=$@
462
463 log DEBUG "Running command in a clean environment: ${cmd}"
464 env -i -- ${cmd}
465 local ret=${?}
466
467 log DEBUG "Returned with code '${ret}'"
468 return ${ret}
469}
470
f5ee091e
MT
471# Executes the given command in background
472cmd_background() {
473 cmd_quiet $@ &
474}
475
476# Prints the PID of the process that was started last
477cmd_background_get_pid() {
478 print "${!}"
479}
480
481cmd_background_result() {
482 local pids=$@
483
484 wait ${pids}
485}
486
b8026986 487# Increase security of the read command
1c6a4e30 488read() {
b8026986
MT
489 builtin read -r $@
490}
491
1c6a4e30 492seq() {
3efecbb3
MT
493 if [ $# -eq 2 ]; then
494 eval echo {${1}..${2}}
495 elif [ $# -eq 3 ]; then
496 eval echo {${1}..${3}..${2}}
497 fi
498}
499
de72bd91
MT
500range() {
501 eval echo {0..$(( ${1} - 1 ))}
502}
503
504count() {
505 local i=0
506
507 while read; do
508 ((i++))
509 done
510
511 echo ${i}
512}
513
1c6a4e30 514which() {
76e6cd51
MT
515 type -P $@
516}
517
fe52c5e0 518# Prints the number of seconds since epoch.
1c6a4e30 519timestamp() {
fe52c5e0
MT
520 date -u "+%s"
521}
522
1c6a4e30 523beautify_time() {
d82cf370
MT
524 local value=${1}
525
526 local unit
527 local limit
528 for unit in s m h d w; do
529 case "${unit}" in
530 s|m|h)
531 limit=60
532 ;;
533 d)
534 limit=24
535 ;;
536 w)
537 limit=7
538 ;;
539 esac
540
541 [ ${value} -lt ${limit} ] && break
542
543 value=$(( ${value} / ${limit} ))
544 done
545
546 echo "${value}${unit}"
547}
711ffac1 548
1c6a4e30 549beautify_bytes() {
711ffac1
MT
550 local value=${1}
551
552 local unit
553 local limit=1024
554 for unit in B k M G T; do
555 [ ${value} -lt ${limit} ] && break
556 value=$(( ${value} / ${limit} ))
557 done
558
559 echo "${value}${unit}"
560}
943e3f7e 561
1c6a4e30 562module_load() {
943e3f7e
MT
563 local module=${1}
564
565 if ! grep -q "^${module}" /proc/modules; then
566 log DEBUG "Loading module '${module}'."
567 modprobe ${module}
568 fi
569}
6b3f9c85 570
1c6a4e30 571binary_exists() {
6b3f9c85
MT
572 local binary=${1}
573
574 if [ -n "$(type -p ${binary})" ]; then
575 return ${EXIT_OK}
576 fi
577
578 return ${EXIT_ERROR}
579}
d76f5107 580
1c6a4e30 581function_exists() {
1e6f187e
MT
582 local function="${1}"
583
584 if [ "$(type -t "${function}")" = "function" ]; then
585 return ${EXIT_TRUE}
586 fi
587
588 return ${EXIT_FALSE}
589}
590
1c6a4e30 591process_kill() {
d76f5107
MT
592 local process=${1}
593
594 if ! isinteger process; then
595 process=$(pidof ${process})
596 fi
597
598 local pid
599 local sig
600 for pid in ${process}; do
601 for sig in 15 9; do
602 [ -d "/proc/${pid}" ] || break
603
604 kill -${sig} ${pid}
605 sleep 1
606 done
607 done
608}
feb76eaf 609
1c6a4e30 610dec() {
feb76eaf
MT
611 local hex=${1}
612
613 if [ "${hex:0:2}" != "0x" ]; then
614 hex="0x${hex}"
615 fi
616
617 printf "%d\n" "${hex}"
618}
3a7fef62 619
1c6a4e30 620chr() {
5cf0edf9
MT
621 local char="${1}"
622
623 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
624
625 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
626}
627
1c6a4e30 628ord() {
5cf0edf9
MT
629 LC_CTYPE="C" printf "%d\n" "'${1}"
630}
631
1c6a4e30 632hex() {
5cf0edf9
MT
633 printf "%X\n" "${1}"
634}
635
1c6a4e30 636network_is_running() {
3a7fef62
MT
637 # Check, if the network service is running.
638 service_is_active network
639}
f80ce052 640
1c6a4e30 641contains_spaces() {
f80ce052
MT
642 local var="$@"
643
644 # Eliminate spaces.
645 local var2=${var// /}
646
647 if [ ${#var} -ne ${#var2} ]; then
648 return ${EXIT_TRUE}
649 fi
650
651 return ${EXIT_FALSE}
0d645497
MT
652}
653
654string_match() {
655 local match=${1}
656 local string=${2}
657
658 [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
f80ce052 659}
5cf0edf9 660
1c6a4e30 661string_split() {
5cf0edf9
MT
662 local string="$@"
663
664 local pos=0
665 while [ ${pos} -lt ${#string} ]; do
666 print "${string:${pos}:1}"
667 pos=$(( ${pos} + 1 ))
668 done
669
670 return ${EXIT_OK}
671}
672
1c6a4e30 673string_reverse() {
5cf0edf9
MT
674 local string="$@"
675
676 local output
677 local pos=0
678 while [ ${pos} -lt ${#string} ]; do
679 output="${string:${pos}:1}${output}"
680 pos=$(( ${pos} + 1 ))
681 done
682
683 print "${output}"
684 return ${EXIT_OK}
685}
686
1c6a4e30 687dec2bin() {
5cf0edf9
MT
688 local number="${1}"
689
690 local output
691
692 local i div
693 for i in 7 6 5 4 3 2 1; do
694 div=$(( 2 ** ${i} ))
695
696 if [ $(( ${number} / ${div} )) -eq 1 ]; then
697 output="${output}1"
698 else
699 output="${output}0"
700 fi
701 number="$(( ${number} % ${div} ))"
702 done
703
704 if [ $(( ${number} % 2 )) -eq 1 ]; then
705 output="${output}1"
706 else
707 output="${output}0"
708 fi
709
710 print "${output}"
711}
712
1c6a4e30 713bin2dec() {
5cf0edf9
MT
714 local string="${1}"
715 local number=0
716
717 local pos=0 char
718 while [ ${pos} -lt ${#string} ]; do
719 char="${string:${pos}:1}"
720 pos=$(( ${pos} + 1 ))
721
722 number=$(( ${number} << 1 ))
723
724 case "${char}" in
725 0) ;;
726 1)
727 number=$(( ${number} + 1 ))
728 ;;
729 *)
730 assert false "Invalid character: ${char}"
731 ;;
732 esac
733 done
734
735 print "${number}"
736 return ${EXIT_OK}
737}
738
1c6a4e30 739char2bin() {
5cf0edf9
MT
740 local dec="$(ord "${1}")"
741
742 dec2bin "${dec}"
743}
744
1c6a4e30 745bin2char() {
5cf0edf9
MT
746 local dec="$(bin2dec "$@")"
747
748 chr "${dec}"
749}
750
1c6a4e30 751bin2hex() {
5cf0edf9
MT
752 local dec="$(bin2dec "$@")"
753
754 dec2hex "${dec}"
755}
756
1c6a4e30 757hex2bin() {
5cf0edf9
MT
758 local dec="$(hex2dec "$@")"
759
760 dec2bin "${dec}"
761}
762
1c6a4e30 763hex2dec() {
5cf0edf9
MT
764 local hex="${1}"
765
766 # Prepend 0x if necessary.
767 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
768
769 printf "%d\n" "${hex}"
770}
771
1c6a4e30 772dec2hex() {
5cf0edf9
MT
773 printf "%02x\n" "${1}"
774}
a95d16fc 775
10b53c87 776# This function just copy config files
a95d16fc 777copy() {
a95d16fc
JS
778 assert [ $# -eq 2 ]
779
780 local src=${1}
781 local dst=${2}
782
287c2e60
MT
783 # Check if we can read from the source
784 if [ ! -r "${src}" ]; then
785 log ERROR "Cannot read ${src}"
786 return ${EXIT_ERROR}
787 fi
788
a95d16fc 789 # Check if ${dst} is a directory
1fade616 790 if [ -d "${dst}" ]; then
9c802e1d 791 log ERROR "${dst} is a directory"
a95d16fc
JS
792 return ${EXIT_ERROR}
793 fi
794
795 if ! fread "${src}" > "${dst}"; then
796 log ERROR "Could not copy data from ${src} to ${dst}"
797 return ${EXIT_ERROR}
798 fi
799}