]> git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
security-policies: Cache output of proposal generators
[people/ms/network.git] / src / functions / functions.util
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
22 # A simple print statement
23 print() {
24 local fmt=${1}; shift
25
26 printf -- "${fmt}\n" "$@"
27 }
28
29 print_indent() {
30 local i=${1}
31 shift
32
33 while (( i-- )); do
34 printf "\t"
35 done
36
37 print "%s" "$@"
38 }
39
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
43 args() {
44 echo "$@" | xargs printf "%s\n"
45 }
46
47 unquote() {
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
62 quote() {
63 print "\"%s\"" "$@"
64 }
65
66 strip() {
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
78 # Print a pretty error message
79 error() {
80 echo -e " ${CLR_RED_B}ERROR${CLR_RESET} : $@" >&2
81 }
82
83 error_log() {
84 log ERROR "$@"
85 }
86
87 # Print a pretty warn message
88 warning() {
89 echo -e " ${CLR_YELLOW_B}WARNING${CLR_RESET}: $@" >&2
90 }
91
92 warning_log() {
93 log WARNING "$@"
94 }
95
96 # Speedup function to avoid a call of the basename binary
97 basename() {
98 echo "${1##*/}"
99 }
100
101 format() {
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
113 format_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
133 parse_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
171 assign() {
172 local key=${1}
173 assert isset key
174 shift
175
176 format "${key}" "%s" "$@"
177 }
178
179 fread() {
180 local file=${1}
181 assert isset file
182
183 [ -r "${file}" ] || return ${EXIT_ERROR}
184
185 print "$(<${file})"
186 }
187
188 fwrite() {
189 local file=${1}
190 assert isset file
191 shift
192
193 if [ -e "${file}" ] && [ ! -w "${file}" ]; then
194 log ERROR "${file}: No such file"
195 return ${EXIT_ERROR}
196 fi
197
198 print "%s" "$@" >> ${file} 2>/dev/null
199 }
200
201 file_exists() {
202 local file=${1}
203
204 [ -e "${file}" ] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
205 }
206
207 file_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
221 file_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
232 make_parent_dir() {
233 local path="${1}"
234
235 local dirname="$(dirname "${path}")"
236 mkdir -p "${dirname}"
237 }
238
239 enabled() {
240 local param=${1}
241
242 list_match "${!param}" yes on true 1
243 }
244
245 mac_generate() {
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 ))
252
253 local output
254 printf -v output "%02x" "${first_byte}"
255
256 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
257
258 # Check if output is valid
259 assert mac_is_valid "${output}"
260
261 echo "${output}"
262 }
263
264 mac_format() {
265 local mac=${1}
266 assert isset mac
267
268 # Remove all colons and make the rest lowercase.
269 mac=${mac//:/}
270 mac=${mac,,}
271
272 local output
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
280 else
281 output=${mac}
282 fi
283
284 assert mac_is_valid ${output}
285
286 print "${output}"
287 }
288
289 mac_is_valid() {
290 local mac=${1}
291
292 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
293 }
294
295 uuid() {
296 echo $(</proc/sys/kernel/random/uuid)
297 }
298
299 abs() {
300 local val=${1}
301
302 if [ ${val} -lt 0 ]; then
303 (( val *= -1 ))
304 fi
305
306 echo ${val}
307 }
308
309 rand() {
310 local uuid="$(uuid)"
311 echo "${uuid//-/}"
312 }
313
314 random() {
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
325 isset() {
326 local var=${1}
327
328 [ -n "${!var}" ]
329 }
330
331 isoneof() {
332 local var=${!1}
333 shift
334
335 list_match "${var}" "$@"
336 }
337
338 isbool() {
339 local var=${1}
340
341 isoneof ${var} 0 1 no yes on off true false
342 }
343
344 isinteger() {
345 local var=${!1}
346
347 [[ ${var} =~ ^[0-9]+$ ]]
348 }
349
350 ismac() {
351 local mac=${!1}
352
353 mac_is_valid ${mac}
354 }
355
356 isipaddress() {
357 local addr=${!1}
358
359 ip_is_valid ${addr}
360 }
361
362 mtu_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
380 backtrace() {
381 local start=1
382
383 echo # Empty line
384 error_log "Backtrace (most recent call in first line):"
385
386 local i source
387 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
388 [ -z "${FUNCNAME[${i}]}" ] && continue
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
397
398 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
399 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
400 done
401 }
402
403 assert() {
404 local assertion="$@"
405
406 if ! ${assertion}; then
407 error_log "Assertion '${assertion}' failed."
408 backtrace
409 exit ${EXIT_ERROR_ASSERT}
410 fi
411
412 return ${EXIT_OK}
413 }
414
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.
417 assert_check_retval() {
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
427 # This function executes the given command and inverses the return code
428 not() {
429 local command="$@"
430
431 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
432 }
433
434 exec_cmd() {
435 local cmd=$@
436
437 log DEBUG "Running command: ${cmd}"
438
439 DEBUG=${DEBUG} \
440 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
441 LOG_FACILITY="${LOG_FACILITY}" \
442 ${SHELL} ${cmd}
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
455 cmd() {
456 local cmd=$@
457
458 log DEBUG "Running command: ${cmd}"
459
460 if ! ${cmd}; then
461 local ret=$?
462
463 log DEBUG "Returned with code '${ret}'"
464 return ${ret}
465 fi
466
467 return ${EXIT_OK}
468 }
469
470 cmd_quiet() {
471 cmd $@ &>/dev/null
472 }
473
474 cmd_exec() {
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
485 cmd_not_implemented() {
486 assert false "not implemented"
487 }
488
489 # Runs a command in a clean environment so that no confidential information
490 # is leaked to any untrusted commands.
491 cmd_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
502 # Executes the given command in background
503 cmd_background() {
504 cmd_quiet $@ &
505 }
506
507 # Prints the PID of the process that was started last
508 cmd_background_get_pid() {
509 print "${!}"
510 }
511
512 cmd_background_result() {
513 local pids=$@
514
515 wait ${pids}
516 }
517
518 # Increase security of the read command
519 read() {
520 builtin read -r $@
521 }
522
523 seq() {
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
531 range() {
532 eval echo {0..$(( ${1} - 1 ))}
533 }
534
535 count() {
536 local i=0
537
538 while read; do
539 ((i++))
540 done
541
542 echo ${i}
543 }
544
545 which() {
546 type -P $@
547 }
548
549 # Prints the number of seconds since epoch.
550 timestamp() {
551 date -u "+%s"
552 }
553
554 beautify_time() {
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 }
579
580 beautify_bytes() {
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 }
592
593 module_load() {
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 }
601
602 binary_exists() {
603 local binary=${1}
604
605 if [ -n "$(type -p ${binary})" ]; then
606 return ${EXIT_OK}
607 fi
608
609 return ${EXIT_ERROR}
610 }
611
612 function_exists() {
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
622 process_kill() {
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 }
640
641 dec() {
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 }
650
651 chr() {
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
659 ord() {
660 LC_CTYPE="C" printf "%d\n" "'${1}"
661 }
662
663 hex() {
664 printf "%X\n" "${1}"
665 }
666
667 network_is_running() {
668 # Check, if the network service is running.
669 service_is_active network
670 }
671
672 contains_spaces() {
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}
683 }
684
685 string_match() {
686 local match=${1}
687 local string=${2}
688
689 [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
690 }
691
692 string_split() {
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
704 string_reverse() {
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
718 dec2bin() {
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
744 bin2dec() {
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
770 char2bin() {
771 local dec="$(ord "${1}")"
772
773 dec2bin "${dec}"
774 }
775
776 bin2char() {
777 local dec="$(bin2dec "$@")"
778
779 chr "${dec}"
780 }
781
782 bin2hex() {
783 local dec="$(bin2dec "$@")"
784
785 dec2hex "${dec}"
786 }
787
788 hex2bin() {
789 local dec="$(hex2dec "$@")"
790
791 dec2bin "${dec}"
792 }
793
794 hex2dec() {
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
803 dec2hex() {
804 printf "%02x\n" "${1}"
805 }
806
807 # This function just copy config files
808 copy() {
809 assert [ $# -eq 2 ]
810
811 local src=${1}
812 local dst=${2}
813
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
820 # Check if ${dst} is a directory
821 if [ -d "${dst}" ]; then
822 log ERROR "${dst} is a directory"
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 }